diff --git a/.github/workflows/build_deploy.yml b/.github/workflows/build_deploy.yml index 30ddb42..fb917ec 100644 --- a/.github/workflows/build_deploy.yml +++ b/.github/workflows/build_deploy.yml @@ -40,6 +40,15 @@ jobs: id: pages uses: actions/configure-pages@v5 + - name: Generate OSV and GHSA feeds + run: bundle exec ruby scripts/generate_feeds.rb + + - name: Validate OSV and GHSA feeds + run: bundle exec ruby scripts/validate_feeds.rb + + - name: Test feed generation and validation + run: bundle exec ruby test/test_feeds.rb + - name: Build with Jekyll # Outputs to the './_site' directory by default run: bundle exec jekyll build --verbose --trace --baseurl "${{ steps.pages.outputs.base_path }}" @@ -47,6 +56,15 @@ jobs: JEKYLL_ENV: production JEKYLL_LOG_LEVEL: debug + - name: Verify published feed endpoints in _site + run: | + test -f _site/feeds/osv/index.json + test -f _site/feeds/ghsa/index.json + for pkg in rnp metanorma cla identity; do + test -f "_site/feeds/osv/${pkg}.json" + test -f "_site/feeds/ghsa/${pkg}.json" + done + - name: Upload artifact # Automatically uploads an artifact from the './_site' directory by default uses: actions/upload-pages-artifact@v4 diff --git a/.gitignore b/.gitignore index 90971d5..8dfd5d1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ _site +feeds # parent-hub/ diff --git a/Gemfile b/Gemfile index e1f5def..27b0618 100644 --- a/Gemfile +++ b/Gemfile @@ -41,4 +41,7 @@ gem "wdm", "~> 0.1.0" if Gem.win_platform? gem "rake" gem "html-proofer" +# For OSV JSON schema validation of generated vulnerability feeds +gem "json_schemer" + gem "webrick", "~> 1.7" diff --git a/Makefile b/Makefile index f4d5826..5e1d551 100644 --- a/Makefile +++ b/Makefile @@ -3,15 +3,25 @@ SHELL := /bin/bash all: _site clean: - rm -rf _site _concepts + rm -rf _site _concepts feeds -_site: | bundle +feeds: | bundle + bundle exec ruby scripts/generate_feeds.rb + bundle exec ruby scripts/validate_feeds.rb + +validate-feeds: | bundle + bundle exec ruby scripts/validate_feeds.rb + +test: feeds + bundle exec ruby test/test_feeds.rb + +_site: feeds | bundle bundle exec jekyll build bundle: bundle -serve: +serve: feeds bundle exec jekyll serve update-init: @@ -20,4 +30,4 @@ update-init: update-modules: git submodule foreach git pull origin master -.PHONY: bundle all open serve clean update-init update-modules +.PHONY: bundle all open serve clean feeds validate-feeds test update-init update-modules diff --git a/_config.yml b/_config.yml index 71f7143..d196fb9 100644 --- a/_config.yml +++ b/_config.yml @@ -105,4 +105,7 @@ exclude: - Makefile - Rakefile - README.adoc + - schemas + - scripts + - test - vendor # for deployment diff --git a/_data/packages.yml b/_data/packages.yml new file mode 100644 index 0000000..0a97dde --- /dev/null +++ b/_data/packages.yml @@ -0,0 +1,65 @@ +# Authoritative tracked-package registry for cve.ribose.com OSV and GHSA feeds. +# Aligned with ribosei/provenance-instance (config/provenance.yaml). +packages: + - repo: rnpgp/rnp + org: rnpgp + name: rnp + tier: A + release_stream: "0.18.x" + ecosystem: GIT + package_name: rnpgp/rnp + purl: pkg:github/rnpgp/rnp + product_names: + - RNP + - rnpgp/rnp + repo_urls: + - https://github.com/rnpgp/rnp + osv_feed_path: /feeds/osv/rnp.json + ghsa_feed_path: /feeds/ghsa/rnp.json + + - repo: metanorma/metanorma + org: metanorma + name: metanorma + tier: A + release_stream: "2.5.x" + ecosystem: RubyGems + package_name: metanorma + purl: pkg:gem/metanorma + product_names: + - metanorma + - Metanorma + repo_urls: + - https://github.com/metanorma/metanorma + osv_feed_path: /feeds/osv/metanorma.json + ghsa_feed_path: /feeds/ghsa/metanorma.json + + - repo: riboseinc/cla + org: riboseinc + name: cla + tier: A + release_stream: "1.x" + ecosystem: GIT + package_name: riboseinc/cla + purl: pkg:github/riboseinc/cla + product_names: + - cla + - CLA + repo_urls: + - https://github.com/riboseinc/cla + osv_feed_path: /feeds/osv/cla.json + ghsa_feed_path: /feeds/ghsa/cla.json + + - repo: ribosei/identity + org: ribosei + name: identity + tier: A + release_stream: "0.4.x" + ecosystem: GIT + package_name: ribosei/identity + purl: pkg:github/ribosei/identity + product_names: + - identity + repo_urls: + - https://github.com/ribosei/identity + osv_feed_path: /feeds/osv/identity.json + ghsa_feed_path: /feeds/ghsa/identity.json diff --git a/schemas/osv-schema.json b/schemas/osv-schema.json new file mode 100644 index 0000000..7729759 --- /dev/null +++ b/schemas/osv-schema.json @@ -0,0 +1,598 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/ossf/osv-schema/main/validation/schema.json", + "title": "Open Source Vulnerability", + "description": "A schema for describing a vulnerability in an open source package. See also https://ossf.github.io/osv-schema/", + "type": "object", + "properties": { + "schema_version": { + "type": "string" + }, + "id": { + "allOf": [ + { + "$ref": "#/$defs/prefix" + }, + { + "$ref": "#/$defs/idFormat" + } + ] + }, + "modified": { + "$ref": "#/$defs/timestamp" + }, + "published": { + "$ref": "#/$defs/timestamp" + }, + "withdrawn": { + "$ref": "#/$defs/timestamp" + }, + "aliases": { + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/$defs/idFormat" + } + }, + "related": { + "type": "array", + "items": { + "$ref": "#/$defs/idFormat" + } + }, + "upstream": { + "type": "array", + "items": { + "$ref": "#/$defs/idFormat" + } + }, + "summary": { + "type": "string" + }, + "details": { + "type": "string" + }, + "severity": { + "$ref": "#/$defs/severity" + }, + "affected": { + "type": [ + "array", + "null" + ], + "items": { + "type": "object", + "properties": { + "package": { + "type": "object", + "properties": { + "ecosystem": { + "$ref": "#/$defs/ecosystemWithSuffix" + }, + "name": { + "type": "string" + }, + "purl": { + "type": "string" + } + }, + "required": [ + "ecosystem", + "name" + ] + }, + "severity": { + "$ref": "#/$defs/severity" + }, + "ranges": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "GIT", + "SEMVER", + "ECOSYSTEM" + ] + }, + "repo": { + "type": "string" + }, + "events": { + "title": "events must contain an introduced object and may contain fixed, last_affected or limit objects", + "type": "array", + "contains": { + "required": [ + "introduced" + ] + }, + "items": { + "type": "object", + "oneOf": [ + { + "type": "object", + "properties": { + "introduced": { + "type": "string" + } + }, + "required": [ + "introduced" + ] + }, + { + "type": "object", + "properties": { + "fixed": { + "type": "string" + } + }, + "required": [ + "fixed" + ] + }, + { + "type": "object", + "properties": { + "last_affected": { + "type": "string" + } + }, + "required": [ + "last_affected" + ] + }, + { + "type": "object", + "properties": { + "limit": { + "type": "string" + } + }, + "required": [ + "limit" + ] + } + ] + }, + "minItems": 1 + }, + "database_specific": { + "type": "object" + } + }, + "allOf": [ + { + "title": "GIT ranges require a repo", + "if": { + "properties": { + "type": { + "const": "GIT" + } + } + }, + "then": { + "required": [ + "repo" + ] + } + }, + { + "title": "GIT ranges must use full-length commit hashes", + "if": { + "properties": { + "type": { + "const": "GIT" + } + } + }, + "then": { + "properties": { + "events": { + "items": { + "oneOf": [ + { + "type": "object", + "properties": { + "introduced": { + "type": "string", + "pattern": "^(0|[a-f0-9]{40}|[a-f0-9]{64})$" + } + }, + "required": [ + "introduced" + ] + }, + { + "type": "object", + "properties": { + "fixed": { + "type": "string", + "pattern": "^(0|[a-f0-9]{40}|[a-f0-9]{64})$" + } + }, + "required": [ + "fixed" + ] + }, + { + "type": "object", + "properties": { + "last_affected": { + "type": "string", + "pattern": "^(0|[a-f0-9]{40}|[a-f0-9]{64})$" + } + }, + "required": [ + "last_affected" + ] + }, + { + "type": "object", + "properties": { + "limit": { + "type": "string", + "pattern": "^(0|[a-f0-9]{40}|[a-f0-9]{64})$" + } + }, + "required": [ + "limit" + ] + } + ] + } + } + } + } + }, + { + "title": "last_affected and fixed events are mutually exclusive", + "if": { + "properties": { + "events": { + "contains": { + "required": [ + "last_affected" + ] + } + } + } + }, + "then": { + "not": { + "properties": { + "events": { + "contains": { + "required": [ + "fixed" + ] + } + } + } + } + } + } + ], + "required": [ + "type", + "events" + ] + } + }, + "versions": { + "type": "array", + "items": { + "type": "string" + } + }, + "ecosystem_specific": { + "type": "object" + }, + "database_specific": { + "type": "object" + } + } + } + }, + "references": { + "type": [ + "array", + "null" + ], + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "ADVISORY", + "ARTICLE", + "DETECTION", + "DISCUSSION", + "REPORT", + "FIX", + "INTRODUCED", + "GIT", + "PACKAGE", + "EVIDENCE", + "WEB" + ] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "type", + "url" + ] + } + }, + "credits": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "contact": { + "type": "array", + "items": { + "type": "string" + } + }, + "type": { + "type": "string", + "enum": [ + "FINDER", + "REPORTER", + "ANALYST", + "COORDINATOR", + "REMEDIATION_DEVELOPER", + "REMEDIATION_REVIEWER", + "REMEDIATION_VERIFIER", + "TOOL", + "SPONSOR", + "OTHER" + ] + } + }, + "required": [ + "name" + ] + } + }, + "database_specific": { + "type": "object" + } + }, + "required": [ + "id", + "modified" + ], + "allOf": [ + { + "if": { + "required": [ + "severity" + ] + }, + "then": { + "properties": { + "affected": { + "items": { + "properties": { + "severity": { + "type": "null" + } + } + } + } + } + } + } + ], + "$defs": { + "ecosystemName": { + "type": "string", + "title": "Currently supported ecosystems", + "description": "These ecosystems are also documented at https://ossf.github.io/osv-schema/#affectedpackage-field", + "enum": [ + "AlmaLinux", + "Alpaquita", + "Alpine", + "Android", + "Azure Linux", + "BellSoft Hardened Containers", + "Bioconductor", + "Bitnami", + "Chainguard", + "CleanStart", + "ConanCenter", + "CRAN", + "crates.io", + "Debian", + "Docker Hardened Images", + "Echo", + "FreeBSD", + "GHC", + "GitHub Actions", + "Go", + "Hackage", + "Hex", + "Homebrew", + "Julia", + "Kubernetes", + "Linux", + "Mageia", + "Maven", + "MinimOS", + "npm", + "NuGet", + "opam", + "openEuler", + "openSUSE", + "OSS-Fuzz", + "Packagist", + "Photon OS", + "Pub", + "PyPI", + "Raspberry Pi OS", + "Red Hat", + "Red Hat Lightwell", + "Rocky Linux", + "Root", + "RubyGems", + "SUSE", + "SwiftURL", + "TuxCare", + "Ubuntu", + "vcpkg", + "VSCode", + "Wolfi", + "WordPress" + ] + }, + "ecosystemSuffix": { + "type": "string", + "pattern": ":.+" + }, + "ecosystemWithSuffix": { + "type": "string", + "title": "Currently supported ecosystems", + "description": "These ecosystems are also documented at https://ossf.github.io/osv-schema/#affectedpackage-field", + "pattern": "^(AlmaLinux|Alpaquita|Alpine|Android|Azure Linux|BellSoft Hardened Containers|Bioconductor|Bitnami|Chainguard|CleanStart|ConanCenter|CRAN|crates\\.io|Debian|Docker Hardened Images|Echo|FreeBSD|GHC|GitHub Actions|Go|Hackage|Hex|Homebrew|Julia|Kubernetes|Linux|Mageia|Maven|MinimOS|npm|NuGet|opam|openEuler|openSUSE|OSS-Fuzz|Packagist|Photon OS|Pub|PyPI|Raspberry Pi OS|Red Hat|Red Hat Lightwell|Rocky Linux|Root|RubyGems|SUSE|SwiftURL|TuxCare|Ubuntu|vcpkg|VSCode|Wolfi|WordPress|GIT)(:.+)?$" + }, + "idFormat": { + "type": "string", + "title": "Permitted identifier characters", + "description": "Identifiers must use only permitted ASCII characters as documented at https://ossf.github.io/osv-schema/#character-set-constraints", + "pattern": "^[a-zA-Z0-9:_.-]+$" + }, + "prefix": { + "type": "string", + "title": "Currently supported home database identifier prefixes", + "description": "These home databases are also documented at https://ossf.github.io/osv-schema/#id-modified-fields", + "pattern": "^(x_|(ASB-A|PUB-A|ALPINE|ALSA|ALBA|ALEA|AZL|BELL|BIT|BREW|CGA|CLEANSTART|CLSA|CURL|CVE|DEBIAN|DHI|DRUPAL|DSA|DLA|ELA|DTSA|ECHO|EEF|FreeBSD|GHSA|GO|GSD|HSEC|JLSEC|KUBE|LBSEC|LSN|MAL|MINI|MGASA|OESA|OSEC|OSV|openSUSE-SU|PHSA|PSF|PYSEC|RHBA|RHEA|RHLW|RHSA|RLSA|RXSA|RPI|RSEC|ROOT|RUSTSEC|SUSE-[SRFO]U|UBUNTU|USN|V8|VCPKG)-)" + }, + "severity": { + "type": [ + "array", + "null" + ], + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "CVSS_V2", + "CVSS_V3", + "CVSS_V4", + "Ubuntu" + ] + }, + "score": { + "type": "string" + }, + "source": { + "type": "string", + "enum": [ + "NVD", + "CNA", + "SELF" + ] + } + }, + "allOf": [ + { + "if": { + "properties": { + "type": { + "const": "CVSS_V2" + } + } + }, + "then": { + "properties": { + "score": { + "pattern": "^((AV:[NAL]|AC:[LMH]|Au:[MSN]|[CIA]:[NPC]|E:(U|POC|F|H|ND)|RL:(OF|TF|W|U|ND)|RC:(UC|UR|C|ND)|CDP:(N|L|LM|MH|H|ND)|TD:(N|L|M|H|ND)|[CIA]R:(L|M|H|ND))/)*(AV:[NAL]|AC:[LMH]|Au:[MSN]|[CIA]:[NPC]|E:(U|POC|F|H|ND)|RL:(OF|TF|W|U|ND)|RC:(UC|UR|C|ND)|CDP:(N|L|LM|MH|H|ND)|TD:(N|L|M|H|ND)|[CIA]R:(L|M|H|ND))$" + } + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "CVSS_V3" + } + } + }, + "then": { + "properties": { + "score": { + "pattern": "^CVSS:3[.][01]/((AV:[NALP]|AC:[LH]|PR:[NLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])/)*(AV:[NALP]|AC:[LH]|PR:[NLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])$" + } + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "CVSS_V4" + } + } + }, + "then": { + "properties": { + "score": { + "pattern": "^CVSS:4[.]0/AV:[NALP]/AC:[LH]/AT:[NP]/PR:[NLH]/UI:[NPA]/VC:[HLN]/VI:[HLN]/VA:[HLN]/SC:[HLN]/SI:[HLN]/SA:[HLN](/E:[XAPU])?(/CR:[XHML])?(/IR:[XHML])?(/AR:[XHML])?(/MAV:[XNALP])?(/MAC:[XLH])?(/MAT:[XNP])?(/MPR:[XNLH])?(/MUI:[XNPA])?(/MVC:[XNLH])?(/MVI:[XNLH])?(/MVA:[XNLH])?(/MSC:[XNLH])?(/MSI:[XNLHS])?(/MSA:[XNLHS])?(/S:[XNP])?(/AU:[XNY])?(/R:[XAUI])?(/V:[XDC])?(/RE:[XLMH])?(/U:(X|Clear|Green|Amber|Red))?$" + } + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "Ubuntu" + } + } + }, + "then": { + "properties": { + "score": { + "enum": [ + "negligible", + "low", + "medium", + "high", + "critical" + ] + } + } + } + } + ], + "required": [ + "type", + "score" + ] + } + }, + "timestamp": { + "type": "string", + "format": "date-time", + "pattern": "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z" + } + }, + "additionalProperties": false +} diff --git a/scripts/generate_feeds.rb b/scripts/generate_feeds.rb new file mode 100644 index 0000000..6f03722 --- /dev/null +++ b/scripts/generate_feeds.rb @@ -0,0 +1,441 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "fileutils" +require "json" +require "net/http" +require "time" +require "uri" +require "yaml" + +ROOT = File.expand_path("..", __dir__) +PACKAGES_FILE = File.join(ROOT, "_data", "packages.yml") +CVES_DIR = File.join(ROOT, "_data", "cves") +ADVISORIES_DIR = File.join(ROOT, "_advisories") +GHSA_DATA_DIR = File.join(ROOT, "_data", "ghsa") +OUT_DIR = File.join(ROOT, "feeds") +BASE_URL = "https://cve.ribose.com" +OSV_SCHEMA_VERSION = "1.6.7" + +def normalize_timestamp(raw) + return nil if raw.nil? || raw.to_s.strip.empty? + + str = raw.to_s.strip + if /\A\d{4}-\d{2}-\d{2}\z/.match?(str) + return "#{str}T00:00:00Z" + end + + Time.parse(str).utc.strftime("%Y-%m-%dT%H:%M:%SZ") +rescue ArgumentError + nil +end + +def load_packages + data = YAML.safe_load_file(PACKAGES_FILE, permitted_classes: [Date, Time]) + packages = data.fetch("packages", []) + raise "No packages defined in #{PACKAGES_FILE}" if packages.empty? + + packages +end + +def parse_advisories + by_cve = Hash.new { |h, k| h[k] = [] } + return by_cve unless Dir.exist?(ADVISORIES_DIR) + + Dir.glob(File.join(ADVISORIES_DIR, "*.adoc")).sort.each do |path| + content = File.read(path, encoding: "UTF-8") + frontmatter = {} + body = content + + if content.start_with?("---\n") || content.start_with?("---\r\n") + parts = content.split(/^---\s*$/, 3) + if parts.length >= 3 + frontmatter = YAML.safe_load(parts[1], permitted_classes: [Date, Time]) || {} + body = parts[2] + end + end + + slug = File.basename(path, ".adoc") + adv_id = (frontmatter["id"] || slug.upcase).to_s.strip + date_str = frontmatter["date"]&.to_s + title = frontmatter["title"]&.to_s&.strip + url = "#{BASE_URL}/advisories/#{slug}/" + + # Extract CVE IDs from body anchors and links (authoritative) and frontmatter + cves = body.scan(/\bCVE-\d{4}-\d+\b/).uniq + if cves.empty? && frontmatter["cve_id"] + cves = [frontmatter["cve_id"].to_s.strip] + end + + cves.each do |cve_id| + by_cve[cve_id] << { + id: adv_id, + slug: slug, + date: date_str, + title: title, + url: url + } + end + end + + by_cve +end + +def normalize_repo_url(url) + url.to_s.strip.downcase.sub(%r{\.git\z}, "").sub(%r{/+\z}, "") +end + +def match_package(affected_entry, packages) + repo_url = normalize_repo_url(affected_entry["repo"]) + product = affected_entry["product"].to_s.strip.downcase + + packages.find do |pkg| + repo_match = !repo_url.empty? && Array(pkg["repo_urls"]).any? { |u| normalize_repo_url(u) == repo_url } + product_match = !product.empty? && Array(pkg["product_names"]).any? { |n| n.to_s.strip.downcase == product } + repo_match || product_match + end +end + +def map_reference_type(ref) + tags = Array(ref["tags"]).map(&:to_s) + url = ref["url"].to_s + + return "ADVISORY" if tags.include?("vendor-advisory") || tags.include?("third-party-advisory") + return "REPORT" if tags.include?("issue-tracking") + return "ADVISORY" if tags.include?("release-notes") + return "FIX" if url.include?("/commit/") && tags.include?("fix") + return "WEB" if tags.include?("related") + + "WEB" +end + +def extract_severity(cna) + osv_severities = [] + base_severities = [] + + Array(cna["metrics"]).each do |metric| + if (v4 = metric["cvssV4_0"]) && v4["vectorString"] + osv_severities << { "type" => "CVSS_V4", "score" => v4["vectorString"].to_s } + base_severities << v4["baseSeverity"].to_s.upcase if v4["baseSeverity"] + end + if (v3 = metric["cvssV3_1"] || metric["cvssV3_0"]) && v3["vectorString"] + osv_severities << { "type" => "CVSS_V3", "score" => v3["vectorString"].to_s } + base_severities << v3["baseSeverity"].to_s.upcase if v3["baseSeverity"] + end + end + + rank = { "CRITICAL" => 4, "HIGH" => 3, "MEDIUM" => 2, "LOW" => 1 } + top_severity = base_severities.max_by { |s| rank.fetch(s, 0) } || "UNKNOWN" + + [osv_severities, top_severity] +end + +def extract_cwe_ids(cna) + cwes = [] + Array(cna["problemTypes"]).each do |pt| + Array(pt["descriptions"]).each do |desc| + cwe = desc["cweId"]&.to_s&.strip + cwes << cwe if cwe && !cwe.empty? + end + end + cwes.uniq +end + +def build_osv_record(cve_path, packages, advisories_by_cve) + raw = JSON.parse(File.read(cve_path, encoding: "UTF-8")) + cve_meta = raw["cveMetadata"] || {} + cve_id = cve_meta["cveId"] || File.basename(cve_path, ".json") + cna = raw.dig("containers", "cna") || {} + linked_advisories = advisories_by_cve[cve_id] || [] + + timestamps = [] + timestamps << normalize_timestamp(cna["datePublic"]) + timestamps << normalize_timestamp(cve_meta["datePublished"]) + linked_advisories.each { |a| timestamps << normalize_timestamp(a[:date]) } + Array(cna["timeline"]).each { |t| timestamps << normalize_timestamp(t["time"]) } + timestamps.compact! + + published = normalize_timestamp(cna["datePublic"]) || + normalize_timestamp(cve_meta["datePublished"]) || + timestamps.min || + "1970-01-01T00:00:00Z" + + modified = normalize_timestamp(cve_meta["dateUpdated"]) || + timestamps.max || + published + + description = cna.dig("descriptions", 0, "value").to_s.strip + summary = cna["title"]&.to_s&.strip + summary = description.lines.first.to_s.strip if summary.nil? || summary.empty? + + osv_severities, top_severity = extract_severity(cna) + cwe_ids = extract_cwe_ids(cna) + + matched_packages = [] + osv_affected = [] + + Array(cna["affected"]).each do |aff| + pkg = match_package(aff, packages) + next unless pkg + + matched_packages << pkg + ranges = [] + versions = [] + + Array(aff["versions"]).each do |ver| + next unless ver["status"].to_s == "affected" + + v_str = ver["version"].to_s.strip + next if v_str.empty? + + if ver["lessThan"] + ranges << { + "type" => "SEMVER", + "events" => [ + { "introduced" => v_str }, + { "fixed" => ver["lessThan"].to_s.strip } + ] + } + elsif ver["lessThanOrEqual"] + ranges << { + "type" => "SEMVER", + "events" => [ + { "introduced" => v_str }, + { "last_affected" => ver["lessThanOrEqual"].to_s.strip } + ] + } + else + versions << v_str + ranges << { + "type" => "SEMVER", + "events" => [ + { "introduced" => v_str }, + { "last_affected" => v_str } + ] + } + end + end + + entry = { + "package" => { + "ecosystem" => pkg["ecosystem"], + "name" => pkg["package_name"], + "purl" => pkg["purl"] + } + } + entry["ranges"] = ranges unless ranges.empty? + entry["versions"] = versions.uniq unless versions.empty? + osv_affected << entry + end + + references = [] + seen_urls = {} + + Array(cna["references"]).each do |ref| + url = ref["url"].to_s.strip + next if url.empty? || seen_urls[url] + + seen_urls[url] = true + references << { + "type" => map_reference_type(ref), + "url" => url + } + end + + linked_advisories.each do |adv| + next if seen_urls[adv[:url]] + + seen_urls[adv[:url]] = true + references << { + "type" => "ADVISORY", + "url" => adv[:url] + } + end + + record = { + "schema_version" => OSV_SCHEMA_VERSION, + "id" => cve_id, + "modified" => modified, + "published" => published, + "summary" => summary, + "details" => description, + "affected" => osv_affected, + "references" => references + } + + related_ids = linked_advisories.map { |a| a[:id] }.uniq + record["related"] = related_ids unless related_ids.empty? + record["severity"] = osv_severities unless osv_severities.empty? + + db_specific = { + "severity" => top_severity, + "cna_assigner" => "Ribose" + } + db_specific["cwe_ids"] = cwe_ids unless cwe_ids.empty? + db_specific["advisory_ids"] = related_ids unless related_ids.empty? + record["database_specific"] = db_specific + + [record, matched_packages.uniq { |p| p["name"] }] +end + +def fetch_upstream_ghsa(repo) + return [] unless ENV["FETCH_UPSTREAM"] == "1" + + uri = URI("https://api.github.com/repos/#{repo}/security-advisories") + req = Net::HTTP::Get.new(uri) + req["Accept"] = "application/vnd.github+json" + req["User-Agent"] = "cve-ribose-feed-generator/1.0" + req["Authorization"] = "Bearer #{ENV['GITHUB_TOKEN']}" if ENV["GITHUB_TOKEN"] && !ENV["GITHUB_TOKEN"].empty? + + res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 5, read_timeout: 10) do |http| + http.request(req) + end + return [] unless res.is_a?(Net::HTTPSuccess) + + parsed = JSON.parse(res.body) + parsed.is_a?(Array) ? parsed : [] +rescue StandardError + [] +end + +def load_ghsa_advisories(pkg) + local_file = File.join(GHSA_DATA_DIR, "#{pkg['name']}.json") + if File.exist?(local_file) + parsed = JSON.parse(File.read(local_file, encoding: "UTF-8")) + return parsed.is_a?(Array) ? parsed : Array(parsed["advisories"]) + end + + fetch_upstream_ghsa(pkg["repo"]) +end + +def write_json(path, data) + FileUtils.mkdir_p(File.dirname(path)) + File.write(path, "#{JSON.pretty_generate(data)}\n", encoding: "UTF-8") +end + +def main + packages = load_packages + advisories_by_cve = parse_advisories + + osv_by_package = Hash.new { |h, k| h[k] = [] } + all_records = [] + + Dir.glob(File.join(CVES_DIR, "*.json")).sort.each do |cve_path| + record, matched_pkgs = build_osv_record(cve_path, packages, advisories_by_cve) + all_records << record + + matched_pkgs.each do |pkg| + osv_by_package[pkg["name"]] << record + end + end + + # Sort records deterministically by ID descending (newest CVEs first) + all_records.sort_by! { |r| r["id"] }.reverse! + + osv_dir = File.join(OUT_DIR, "osv") + ghsa_dir = File.join(OUT_DIR, "ghsa") + FileUtils.rm_rf(OUT_DIR) + FileUtils.mkdir_p(osv_dir) + FileUtils.mkdir_p(ghsa_dir) + + # 1. Individual OSV records: /feeds/osv/.json + all_records.each do |record| + write_json(File.join(osv_dir, "#{record['id']}.json"), record) + end + + # 2. Per-package OSV and GHSA feeds + index_packages = [] + by_purl = {} + ghsa_index_packages = [] + + packages.each do |pkg| + pkg_vulns = osv_by_package[pkg["name"]].sort_by { |r| r["id"] }.reverse + pkg_meta = { + "repo" => pkg["repo"], + "name" => pkg["name"], + "tier" => pkg["tier"], + "release_stream" => pkg["release_stream"], + "ecosystem" => pkg["ecosystem"], + "purl" => pkg["purl"] + } + + osv_feed = { + "schema_version" => OSV_SCHEMA_VERSION, + "package" => pkg_meta, + "vulns" => pkg_vulns + } + write_json(File.join(osv_dir, "#{pkg['name']}.json"), osv_feed) + + osv_url = "#{BASE_URL}#{pkg['osv_feed_path']}" + ghsa_url = "#{BASE_URL}#{pkg['ghsa_feed_path']}" + vuln_ids = pkg_vulns.map { |v| v["id"] } + + index_packages << { + "repo" => pkg["repo"], + "name" => pkg["name"], + "tier" => pkg["tier"], + "release_stream" => pkg["release_stream"], + "ecosystem" => pkg["ecosystem"], + "purl" => pkg["purl"], + "osv_feed_url" => osv_url, + "ghsa_feed_url" => ghsa_url, + "vulnerability_count" => pkg_vulns.length, + "vulnerability_ids" => vuln_ids + } + + by_purl[pkg["purl"]] = { + "repo" => pkg["repo"], + "name" => pkg["name"], + "osv_feed_url" => osv_url, + "ghsa_feed_url" => ghsa_url, + "vulnerability_ids" => vuln_ids + } + + ghsa_advisories = load_ghsa_advisories(pkg) + ghsa_feed = { + "package" => pkg_meta, + "advisories" => ghsa_advisories + } + write_json(File.join(ghsa_dir, "#{pkg['name']}.json"), ghsa_feed) + + ghsa_index_packages << { + "repo" => pkg["repo"], + "name" => pkg["name"], + "tier" => pkg["tier"], + "purl" => pkg["purl"], + "ghsa_feed_url" => ghsa_url, + "advisory_count" => ghsa_advisories.length + } + end + + # 3. OSV index: /feeds/osv/index.json + osv_index = { + "schema_version" => OSV_SCHEMA_VERSION, + "base_url" => BASE_URL, + "packages" => index_packages, + "by_purl" => by_purl, + "vulns" => all_records.map do |r| + { + "id" => r["id"], + "modified" => r["modified"], + "published" => r["published"], + "summary" => r["summary"], + "severity" => r.dig("database_specific", "severity") || "UNKNOWN", + "purls" => r["affected"].map { |a| a.dig("package", "purl") }.compact.uniq, + "url" => "#{BASE_URL}/feeds/osv/#{r['id']}.json" + } + end + } + write_json(File.join(osv_dir, "index.json"), osv_index) + + # 4. GHSA index: /feeds/ghsa/index.json + ghsa_index = { + "base_url" => BASE_URL, + "packages" => ghsa_index_packages + } + write_json(File.join(ghsa_dir, "index.json"), ghsa_index) + + puts "Generated OSV and GHSA feeds for #{packages.length} packages (#{all_records.length} OSV records) in #{OUT_DIR}" +end + +main if __FILE__ == $PROGRAM_NAME diff --git a/scripts/validate_feeds.rb b/scripts/validate_feeds.rb new file mode 100644 index 0000000..6c795a9 --- /dev/null +++ b/scripts/validate_feeds.rb @@ -0,0 +1,104 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "json" +require "json_schemer" +require "yaml" + +ROOT = File.expand_path("..", __dir__) +SCHEMA_PATH = File.join(ROOT, "schemas", "osv-schema.json") +PACKAGES_FILE = File.join(ROOT, "_data", "packages.yml") + +def validate_osv_record(schemer, record, context_label, errors) + issues = schemer.validate(record).to_a + return if issues.empty? + + issues.each do |issue| + errors << "#{context_label}: #{issue['error'] || issue['details'] || issue.inspect} (at #{issue['data_pointer']})" + end +end + +def main + feeds_dir = ARGV[0] ? File.expand_path(ARGV[0]) : File.join(ROOT, "feeds") + schema = JSON.parse(File.read(SCHEMA_PATH, encoding: "UTF-8")) + schemer = JSONSchemer.schema(schema) + packages = YAML.safe_load_file(PACKAGES_FILE, permitted_classes: [Date, Time]).fetch("packages", []) + + errors = [] + validated_records = 0 + + osv_dir = File.join(feeds_dir, "osv") + ghsa_dir = File.join(feeds_dir, "ghsa") + + osv_index_path = File.join(osv_dir, "index.json") + unless File.exist?(osv_index_path) + errors << "Missing OSV index file: #{osv_index_path}" + else + osv_index = JSON.parse(File.read(osv_index_path, encoding: "UTF-8")) + errors << "OSV index missing 'packages' array" unless osv_index["packages"].is_a?(Array) + errors << "OSV index missing 'by_purl' object" unless osv_index["by_purl"].is_a?(Hash) + errors << "OSV index missing 'vulns' array" unless osv_index["vulns"].is_a?(Array) + end + + ghsa_index_path = File.join(ghsa_dir, "index.json") + unless File.exist?(ghsa_index_path) + errors << "Missing GHSA index file: #{ghsa_index_path}" + else + ghsa_index = JSON.parse(File.read(ghsa_index_path, encoding: "UTF-8")) + errors << "GHSA index missing 'packages' array" unless ghsa_index["packages"].is_a?(Array) + end + + package_names = packages.map { |p| p["name"].to_s } + + packages.each do |pkg| + name = pkg["name"].to_s + osv_pkg_path = File.join(osv_dir, "#{name}.json") + if File.exist?(osv_pkg_path) + data = JSON.parse(File.read(osv_pkg_path, encoding: "UTF-8")) + unless data["package"].is_a?(Hash) && data["package"]["purl"] == pkg["purl"] + errors << "#{osv_pkg_path}: missing or mismatched package.purl (expected #{pkg['purl']})" + end + if data["vulns"].is_a?(Array) + data["vulns"].each_with_index do |vuln, idx| + validate_osv_record(schemer, vuln, "#{osv_pkg_path}#vulns[#{idx}]", errors) + validated_records += 1 + end + else + errors << "#{osv_pkg_path}: 'vulns' must be an Array" + end + else + errors << "Missing per-package OSV feed: #{osv_pkg_path}" + end + + ghsa_pkg_path = File.join(ghsa_dir, "#{name}.json") + if File.exist?(ghsa_pkg_path) + data = JSON.parse(File.read(ghsa_pkg_path, encoding: "UTF-8")) + unless data["package"].is_a?(Hash) && data["package"]["purl"] == pkg["purl"] + errors << "#{ghsa_pkg_path}: missing or mismatched package.purl (expected #{pkg['purl']})" + end + errors << "#{ghsa_pkg_path}: 'advisories' must be an Array" unless data["advisories"].is_a?(Array) + else + errors << "Missing per-package GHSA feed: #{ghsa_pkg_path}" + end + end + + # Validate all standalone OSV record files in feeds/osv/*.json + Dir.glob(File.join(osv_dir, "*.json")).sort.each do |path| + base = File.basename(path, ".json") + next if base == "index" || package_names.include?(base) + + record = JSON.parse(File.read(path, encoding: "UTF-8")) + validate_osv_record(schemer, record, path, errors) + validated_records += 1 + end + + if errors.any? + warn "OSV/GHSA feed validation failed with #{errors.length} error(s):" + errors.each { |e| warn " - #{e}" } + exit 1 + end + + puts "Validated #{validated_records} OSV record(s) and #{packages.length} package feeds against OSV JSON Schema." +end + +main if __FILE__ == $PROGRAM_NAME diff --git a/test/test_feeds.rb b/test/test_feeds.rb new file mode 100644 index 0000000..618da22 --- /dev/null +++ b/test/test_feeds.rb @@ -0,0 +1,89 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "fileutils" +require "json" +require "minitest/autorun" +require "open3" +require "tmpdir" + +ROOT = File.expand_path("..", __dir__) +FEEDS_DIR = File.join(ROOT, "feeds") +GENERATE_SCRIPT = File.join(ROOT, "scripts", "generate_feeds.rb") +VALIDATE_SCRIPT = File.join(ROOT, "scripts", "validate_feeds.rb") + +class TestFeeds < Minitest::Test + def setup + _, status = Open3.capture2e(RbConfig.ruby, GENERATE_SCRIPT) + assert status.success?, "generate_feeds.rb must succeed" + end + + def test_tier_a_endpoints_exist + %w[rnp metanorma cla identity].each do |pkg| + osv_path = File.join(FEEDS_DIR, "osv", "#{pkg}.json") + ghsa_path = File.join(FEEDS_DIR, "ghsa", "#{pkg}.json") + assert File.exist?(osv_path), "Expected #{osv_path} to exist" + assert File.exist?(ghsa_path), "Expected #{ghsa_path} to exist" + + osv = JSON.parse(File.read(osv_path, encoding: "UTF-8")) + assert_kind_of Array, osv["vulns"] + assert_equal pkg, osv.dig("package", "name") + + ghsa = JSON.parse(File.read(ghsa_path, encoding: "UTF-8")) + assert_kind_of Array, ghsa["advisories"] + assert_equal pkg, ghsa.dig("package", "name") + end + end + + def test_osv_index_keyed_by_package_and_purl + index = JSON.parse(File.read(File.join(FEEDS_DIR, "osv", "index.json"), encoding: "UTF-8")) + assert_equal "https://cve.ribose.com", index["base_url"] + + expected_purls = { + "rnp" => "pkg:github/rnpgp/rnp", + "metanorma" => "pkg:gem/metanorma", + "cla" => "pkg:github/riboseinc/cla", + "identity" => "pkg:github/ribosei/identity" + } + + expected_purls.each do |pkg, purl| + assert index["by_purl"].key?(purl), "Expected index by_purl to include #{purl}" + assert_equal "https://cve.ribose.com/feeds/osv/#{pkg}.json", index.dig("by_purl", purl, "osv_feed_url") + assert_equal "https://cve.ribose.com/feeds/ghsa/#{pkg}.json", index.dig("by_purl", purl, "ghsa_feed_url") + end + end + + def test_rnp_osv_records_contain_expected_cves + rnp = JSON.parse(File.read(File.join(FEEDS_DIR, "osv", "rnp.json"), encoding: "UTF-8")) + ids = rnp["vulns"].map { |v| v["id"] } + %w[CVE-2025-13470 CVE-2023-29480 CVE-2023-29479 CVE-2021-33589].each do |cve| + assert_includes ids, cve + assert File.exist?(File.join(FEEDS_DIR, "osv", "#{cve}.json")) + end + + cve_2025 = rnp["vulns"].find { |v| v["id"] == "CVE-2025-13470" } + assert_equal "HIGH", cve_2025.dig("database_specific", "severity") + assert_equal "pkg:github/rnpgp/rnp", cve_2025.dig("affected", 0, "package", "purl") + assert_includes cve_2025.dig("affected", 0, "versions"), "0.18.0" + assert_includes cve_2025["related"], "RA-2025-11-20" + end + + def test_validator_passes_on_generated_feeds + out, status = Open3.capture2e(RbConfig.ruby, VALIDATE_SCRIPT, FEEDS_DIR) + assert status.success?, "validate_feeds.rb should pass: #{out}" + end + + def test_validator_rejects_malformed_osv_record + Dir.mktmpdir do |tmpdir| + FileUtils.cp_r(File.join(FEEDS_DIR, "osv"), tmpdir) + FileUtils.cp_r(File.join(FEEDS_DIR, "ghsa"), tmpdir) + + bad_record_path = File.join(tmpdir, "osv", "CVE-2025-99999.json") + File.write(bad_record_path, JSON.pretty_generate({ "id" => "INVALID-PREFIX-123" })) + + out, status = Open3.capture2e(RbConfig.ruby, VALIDATE_SCRIPT, tmpdir) + refute status.success?, "validate_feeds.rb must fail on malformed OSV record" + assert_includes out, "validation failed" + end + end +end