The user wants an "Engineer a deployment artifacts catalog" system.
This system needs to expose three specific things for each artifact:
Provenance: Where did it come from? (Build info, git commit, author, timestamp, CI job).
Dependencies: What does it rely on? (Libraries, base images, other services, environment variables).
Rollback Scripts: How do we revert to a previous state? (SQL migrations, config changes, executable scripts).
I. Conceptual Design & Architecture
Goal: A centralized, queryable repository (or interface) that makes deployment safe and observable.
Components:
Storage: Need a database (metadata) and blob storage (binaries/scripts).
Ingestion: CI/CD plugins or CLI tools to push artifacts.
API/UI: How users interact with it.
Security: Signing (SBOM, SLSA provenance).
Data Model (The "Artifact"):
ID (SHA256 hash is best).
Name/Type.
Version.
Provenance payload (in-toto/SLSA format).
Dependency graph (SBOM - SPDX/CycloneDX).
Link to Rollback Artifact.
Technology Stack:
Backend: Python (FastAPI) or Go (standard for infra tools). Let's go with Python/FastAPI for readability and quick prototyping, or Go for performance. Let's stick to a conceptual implementation in Python/FastAPI as it's very accessible for "engineering" demonstrations.
DB: PostgreSQL (relational data, JSONB for metadata).
Storage: S3 (MinIO for local dev).
Standards: SLSA (Supply-chain Levels for Software Artifacts), CycloneDX (SBOM).
II. Structuring the Solution
I should provide a solution that covers:
Data Schema: How to store the info.
API Interface: How to get the info.
Ingestion Logic: How the CI/CD populates this catalog.
Provenance: Needs to capture Git SHA, Build Trigger, Builder ID.
Dependencies: Needs to list software packages (npm, pip, jar) and infrastructure dependencies (Postgres v14, Redis v6).
Rollback: Instead of just a script URL, maybe a pointer to another artifact? Or an inline bash/sql script. Let's assume a script bundled with the artifact or a reference to a known rollback version.
IV. Refining the "Engineering" Aspect
A generic description isn't enough. I need to provide:
Core Data Structure (JSON Schema/SQL).
API Specification (OpenAPI/Python code).
The Metadata Manifest (The file format).
CLI/CI Interaction (Example workflow).
V. Developing the Code Artifacts
The Manifest (manifest.json): This is the heart of the catalog entry.
The API (Python/FastAPI): Endpoints for GET /artifacts/{id}, POST /artifacts.
The DB Model (SQLAlchemy/Pydantic).
VI. Addressing the Specific Requirements
Provenance: Use a structure inspired by in-toto/SLSA statements.
Dependencies: Use a simplified CycloneDX structure.
Rollback: Store a reference to a executable artifact (e.g., rollback.sh).
VII. Review and Refine
Critique: Is it secure?
Fix: Mention signing artifacts (Cosign).
Critique: Is it practical?
Fix: Ensure the rollback script is part of the upload process.
VIII. Final Output Structure
Architecture Overview: High-level diagram.
The Artifact Manifest (The Core Standard): YAML/JSON definition.
Backend Implementation: Python/FastAPI implementation of the catalog.
CI/CD Integration: How to generate and upload the data.
Rollback Logic: How the catalog facilitates the "undo".
(Self-Correction during drafting): Don't just write a file server. The key is the metadata catalog. The files might live in S3/JFrog, but this system maps them. I will assume this system manages the metadata and points to the storage locations.
Let's polish the Python code to be copy-pasteable.
IX. Final Polish
Add a section on "Operational Workflow" so the user knows how to use it.
CI Build -> Generates Manifest.
Upload Artifact + Script to Blob Store.
POST Manifest to Catalog.
Deploy Process queries Catalog.
This looks solid. Proceed with generating the response.
This solution designs a Deployment Artifacts Catalog engineered to be the single source of truth for your release train. It moves beyond simple file storage to treat every deployment as a structured event with verifiable history (provenance), a software bill of materials (dependencies), and a tactical recovery plan (rollback).
1. Architecture Overview
The system consists of three layers:
The Artifact Storage (Blob): Immutable storage for binaries (S3, Artifactory, Nexus).
The Catalog (Metadata): A searchable index linking artifacts to their context (The solution below).
The Execution Agent: The tool (Spinnaker, ArgoCD, Bash) that reads the catalog to deploy or rollback.
2. The Catalog Data Model (The "Packing Slip")
We will use a standardised JSON schema for every artifact entry. This ensures that regardless of language (Java, Go, JS), the catalog understands the payload.
The Deployment tool queries the catalog to get the current state and the target state.
Fetch:GET /catalog/srv-payments/1.0.1
Verify: Check sha256 matches the binary pulled from the repository.
Audit: Log the provenance.git_commit to the deployment log.
Phase C: The Rollback (Recovery)
If 1.0.1 causes a runtime error:
Analyze: Check dependencies. Did critical_vulns change? No. Did base image change? Yes.
Execute:GET /catalog/srv-payments/rollback/1.0.0
Action: The API returns the location of the rollback-1.0.0.sh script and the SQL down-migration file.
Safety: The CD runner downloads the script, verifies it is signed (optional security layer), and executes it.
5. Engineering Best Practices for this Catalog
Immutable Storage: Never delete old artifact metadata. Even if version 1.0.0 is ancient, keeping its provenance helps audit "what changed" years later.
SBOM Integration: Ensure dependencies.sbom_location points to a generated CycloneDX or SPDX file. This fulfills supply chain security requirements (like US Executive Order 14028).
Rollback Script Bundling: Do not store rollback scripts in a separate git repo. Bundle them inside the artifact or store them alongside the binary in the object store. If the git server is down during an outage, you still need access to the rollback script.
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel, HttpUrl
from typing import List, Optional
from datetime import datetime
import hashlib
# --- Data Models ---
class Provenance(BaseModel):
git_commit: str
git_branch: str
ci_run_id: str
builder_image: str
build_log_url: HttpUrl
class Dependency(BaseModel):
sbom_format: str
sbom_location: str
base_image: str
critical_vulns: int
class Rollback(BaseModel):
strategy: str # e.g., 'blue_green', 'canary', 'replace'
script_location: str
sql_backward_path: Optional[str] = None
previous_stable_version: str
class Artifact(BaseModel):
artifact_id: str
version: str
timestamp: datetime = datetime.utcnow()
sha256: str
provenance: Provenance
dependencies: Dependency
rollback: Rollback
# --- Mock Database ---
# In production, replace with PostgreSQL or MongoDB
db_artifacts = {}
# --- App Initialization ---
app = FastAPI(title="Deployment Artifacts Catalog")
# --- Helper: Integrity Check ---
def verify_integrity(artifact: Artifact):
# In a real scenario, you would check if the SHA matches the uploaded binary
print(f"Verifying integrity for {artifact.artifact_id}...")
return True
# --- Endpoints ---
@app.post("/catalog/register", status_code=201)
def register_artifact(artifact: Artifact, background_tasks: BackgroundTasks):
"""
CI/CD Pipeline calls this after a successful build.
It registers the artifact metadata.
"""
key = f"{artifact.artifact_id}-{artifact.version}"
if key in db_artifacts:
raise HTTPException(status_code=400, detail="Artifact version already exists.")
# Store in catalog
db_artifacts[key] = artifact.dict()
# Trigger background tasks (e.g., notify Slack, trigger scanner)
background_tasks.add_task(log_registration, artifact)
return {"status": "registered", "catalog_id": key}
@app.get("/catalog/{artifact_id}/{version}", response_model=Artifact)
def get_artifact_details(artifact_id: str, version: str):
"""
Retrieve full metadata for deployment or auditing.
"""
key = f"{artifact_id}-{version}"
if key not in db_artifacts:
raise HTTPException(status_code=404, detail="Artifact not found in catalog")
return db_artifacts[key]
@app.get("/catalog/{artifact_id}/rollback/{target_version}")
def get_rollback_instructions(artifact_id: str, target_version: str):
"""
The 'Panic Button' endpoint.
Returns the specific scripts and steps needed to revert to a specific version.
"""
key = f"{artifact_id}-{target_version}"
if key not in db_artifacts:
raise HTTPException(status_code=404, detail="Target version not found")
target = db_artifacts[key]
return {
"action": "ROLLBACK_INITIATED",
"target_version": target_version,
"rollback_script_url": target['rollback']['script_location'],
"db_migration_script": target['rollback']['sql_backward_path'],
"integrity_hash": target['sha256'],
"instructions": f"Execute script at {target['rollback']['script_location']} to revert."
}
@app.get("/search")
def search_provenance(git_commit: str = None, min_vulns: int = None):
"""
Query the catalog.
Example: Find all artifacts built from a specific commit (useful for hotfixes).
"""
results = []
for art in db_artifacts.values():
match = True
if git_commit and art['provenance']['git_commit'] != git_commit:
match = False
if min_vulns is not None and art['dependencies']['critical_vulns'] < min_vulns:
match = False
if match:
results.append(art)
return results
def log_registration(artifact: Artifact):
print(f"LOG: New artifact registered {artifact.artifact_id} v{artifact.version}")
# Run with: uvicorn catalog:app --reload