diff --git a/Dockerfile.agent b/Dockerfile.agent index 756719e..2272542 100644 --- a/Dockerfile.agent +++ b/Dockerfile.agent @@ -80,9 +80,6 @@ COPY --from=builder /app/README.md /app/README.md COPY --from=builder /app/docs /app/docs ENV HELP_DOCS_PATH=/app -# Ensure SSH key directory exists -RUN mkdir -p /data/compliance-scanner/ssh - EXPOSE 3001 3002 # Seeds /nix (fresh volume) from the bootstrap tarball, then runs the agent. diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index c17011d..9f18415 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -113,8 +113,13 @@ impl ComplianceAgent { trigger: compliance_core::models::ScanTrigger, ) -> Result<(), crate::error::AgentError> { let db = self.db_pool.for_tenant_id(tenant_id).await?; - let orchestrator = - PipelineOrchestrator::new(self.config.clone(), db, self.llm.clone(), self.http.clone()); + let orchestrator = PipelineOrchestrator::new( + self.config.clone(), + tenant_id, + db, + self.llm.clone(), + self.http.clone(), + ); let started = chrono::Utc::now(); orchestrator.run_target(target_id, trigger.clone()).await?; self.emit_usage( @@ -150,8 +155,13 @@ impl ComplianceAgent { })?; let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code); - let orchestrator = - PipelineOrchestrator::new(self.config.clone(), db, self.llm.clone(), self.http.clone()); + let orchestrator = PipelineOrchestrator::new( + self.config.clone(), + tenant_id, + db, + self.llm.clone(), + self.http.clone(), + ); orchestrator .run_pr_review(&repo, repo_id, pr_number, base_sha, head_sha) .await diff --git a/compliance-agent/src/api/handlers/chat.rs b/compliance-agent/src/api/handlers/chat.rs index a402cd2..9500b49 100644 --- a/compliance-agent/src/api/handlers/chat.rs +++ b/compliance-agent/src/api/handlers/chat.rs @@ -144,6 +144,9 @@ pub async fn build_embeddings( // the JWT/dev context isn't available inside detached tasks. let db = tenant_db(&agent, &tenant).await?; let agent_clone = (*agent).clone(); + // The detached task has no request context, so carry the tenant id with it — + // it selects the tenant's own checkout directory. + let tenant_id = tenant.0.tenant_id.clone(); tokio::spawn(async move { let repo = match db .onboarded_targets() @@ -202,13 +205,12 @@ pub async fn build_embeddings( } }; let view = crate::pipeline::repo_view::RepoView::from_target(&repo, code); - let creds = crate::pipeline::git::RepoCredentials { - ssh_key_path: Some(agent_clone.config.ssh_key_path.clone()), - auth_token: view.auth_token.clone(), - auth_username: view.auth_username.clone(), - }; - let git_ops = - crate::pipeline::git::GitOps::new(&agent_clone.config.git_clone_base_path, creds); + let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view); + let git_ops = crate::pipeline::git::GitOps::new( + &agent_clone.config.git_clone_base_path, + &tenant_id, + creds, + ); let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) { Ok(p) => p, Err(e) => { diff --git a/compliance-agent/src/api/handlers/graph.rs b/compliance-agent/src/api/handlers/graph.rs index 937efd3..aca6e2c 100644 --- a/compliance-agent/src/api/handlers/graph.rs +++ b/compliance-agent/src/api/handlers/graph.rs @@ -261,17 +261,19 @@ pub async fn get_file_content( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .ok_or(StatusCode::NOT_FOUND)?; - let base_path = std::path::Path::new(&agent.config.git_clone_base_path); - let file_path = base_path.join(&repo.name).join(¶ms.path); + // The checkout is per tenant — read only from the caller's own. + let repo_dir = crate::pipeline::git::clone_dir( + std::path::Path::new(&agent.config.git_clone_base_path), + &tenant.0.tenant_id, + &repo.name, + ); + let file_path = repo_dir.join(¶ms.path); // Security: ensure we don't escape the repo directory let canonical = file_path .canonicalize() .map_err(|_| StatusCode::NOT_FOUND)?; - let base_canonical = base_path - .join(&repo.name) - .canonicalize() - .map_err(|_| StatusCode::NOT_FOUND)?; + let base_canonical = repo_dir.canonicalize().map_err(|_| StatusCode::NOT_FOUND)?; if !canonical.starts_with(&base_canonical) { return Err(StatusCode::FORBIDDEN); } @@ -315,6 +317,9 @@ pub async fn trigger_build( ) -> Result, StatusCode> { let db = tenant_db(&agent, &tenant).await?; let agent_clone = (*agent).clone(); + // The detached task has no request context, so carry the tenant id with it — + // it selects the tenant's own checkout directory. + let tenant_id = tenant.0.tenant_id.clone(); tokio::spawn(async move { let repo = match db .onboarded_targets() @@ -336,13 +341,12 @@ pub async fn trigger_build( } }; let view = crate::pipeline::repo_view::RepoView::from_target(&repo, code); - let creds = crate::pipeline::git::RepoCredentials { - ssh_key_path: Some(agent_clone.config.ssh_key_path.clone()), - auth_token: view.auth_token.clone(), - auth_username: view.auth_username.clone(), - }; - let git_ops = - crate::pipeline::git::GitOps::new(&agent_clone.config.git_clone_base_path, creds); + let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view); + let git_ops = crate::pipeline::git::GitOps::new( + &agent_clone.config.git_clone_base_path, + &tenant_id, + creds, + ); let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) { Ok(p) => p, Err(e) => { diff --git a/compliance-agent/src/api/handlers/health.rs b/compliance-agent/src/api/handlers/health.rs index fbdfd26..1d934aa 100644 --- a/compliance-agent/src/api/handlers/health.rs +++ b/compliance-agent/src/api/handlers/health.rs @@ -10,18 +10,6 @@ pub async fn health() -> Json { Json(serde_json::json!({ "status": "ok" })) } -/// GET /api/v1/settings/ssh-public-key — the agent's SSH deploy public key, -/// for adding as a read-only deploy key on private git targets. -#[tracing::instrument(skip_all)] -pub async fn get_ssh_public_key( - axum::extract::Extension(agent): AgentExt, -) -> Result, axum::http::StatusCode> { - let public_path = format!("{}.pub", agent.config.ssh_key_path); - let public_key = - std::fs::read_to_string(&public_path).map_err(|_| axum::http::StatusCode::NOT_FOUND)?; - Ok(Json(serde_json::json!({ "public_key": public_key.trim() }))) -} - #[tracing::instrument(skip_all)] pub async fn stats_overview( axum::extract::Extension(agent): AgentExt, diff --git a/compliance-agent/src/api/handlers/werkbank_jobs.rs b/compliance-agent/src/api/handlers/werkbank_jobs.rs index 03c262a..643a770 100644 --- a/compliance-agent/src/api/handlers/werkbank_jobs.rs +++ b/compliance-agent/src/api/handlers/werkbank_jobs.rs @@ -1,16 +1,21 @@ //! Werkbank runner endpoints (`/api/v1/werkbank/jobs/*`). //! //! The pull API a Werkbank runner talks to: lease a job, heartbeat while it runs, -//! and post the result back. Machine auth is a **static bearer token** -//! (`WERKBANK_RUNNER_TOKEN`) — not a Keycloak JWT, because a runner acts across -//! tenants (each request names its `tenant`). Routes are only mounted when the -//! token is configured; with none set they don't exist (404). +//! and post the result back. Machine auth is a portal-issued API key bound to +//! one tenant (scope `werkbank:runner`) — not a Keycloak JWT, because a runner +//! is a machine. +//! +//! A deployment-wide static bearer (`WERKBANK_RUNNER_TOKEN`) is still accepted +//! on a **dev** deployment, where it is the only option before the platform is +//! wired up. It names no tenant, so it can act for any of them; a hardened +//! deployment ([`compliance_core::config::AppEnv::is_hardened`]) refuses it. +//! Routes are only mounted when one of the two is configured. //! //! On completion the runner's findings are persisted against the job's target, //! so a job run by a remote runner lands the same findings an in-process run //! would (WB-05, the control-plane cut-over). -use axum::extract::{Extension, Path, Request}; +use axum::extract::{Extension, Path, Query, Request}; use axum::http::{header, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; @@ -52,11 +57,7 @@ pub async fn require_runner_token( return (StatusCode::UNAUTHORIZED, "API keys need a tenant registry").into_response(); }; return match registry.verify_api_key(presented).await { - Ok(v) - if v.valid - && (v.scopes.iter().any(|s| s == "werkbank:runner") - || v.product == registry.product()) => - { + Ok(v) if runner_key_accepted(v.valid, &v.scopes) => { // The key is tenant-scoped: every request must name that tenant. let mut request = request; request.extensions_mut().insert(RunnerTenant(v.tenant_id)); @@ -73,7 +74,21 @@ pub async fn require_runner_token( } }; } - // Static runner token (pre-platform deployments). + // Static runner token (pre-platform deployments). It is bound to no tenant, + // so a holder can act for every tenant at once — acceptable on a laptop, + // never where real tenants live. + if agent.config.app_env.is_hardened() { + tracing::warn!( + app_env = agent.config.app_env.as_str(), + "static WERKBANK_RUNNER_TOKEN presented on a hardened deployment — refused" + ); + return ( + StatusCode::UNAUTHORIZED, + "The static runner token is not accepted in this deployment; \ + use a portal-issued API key with the werkbank:runner scope", + ) + .into_response(); + } let Some(expected) = agent.config.werkbank_runner_token.as_ref() else { return (StatusCode::UNAUTHORIZED, "Invalid runner token").into_response(); }; @@ -83,6 +98,19 @@ pub async fn require_runner_token( next.run(request).await } +/// The scope a portal-issued API key must carry to drive the runner endpoints. +const RUNNER_SCOPE: &str = "werkbank:runner"; + +/// Whether a verified API key may drive the runner endpoints. +/// +/// The scope is **required**. This used to also accept any key whose `product` +/// was this product, which made every `pruefwerk` API key — a dashboard key, a +/// reporting key — a runner key that could lease and complete other tenants' +/// jobs. Product membership says who issued the key, not what it may do. +fn runner_key_accepted(valid: bool, scopes: &[String]) -> bool { + valid && scopes.iter().any(|s| s == RUNNER_SCOPE) +} + /// Tenant a registry API key is bound to (set by [`require_runner_token`]). /// Absent for the static runner token (pre-platform deployments). #[derive(Clone, Debug)] @@ -179,17 +207,47 @@ pub async fn complete( Ok(Json(CompleteResponse { recorded })) } -/// `GET /api/v1/werkbank/artifacts/{hash}` — serve a content-addressed blob (the -/// program a runner needs to load). The hash is validated against traversal by -/// [`crate::ingest::blob::read_blob`]; a runner fetches this for a job's `blob` -/// input. +/// Which tenant's artifact store a fetch reads from. +#[derive(Debug, Deserialize)] +pub struct ArtifactQuery { + /// Required with the static runner token, which names no tenant of its own. + /// With a tenant-bound API key it is optional, and must match the key. + pub tenant: Option, +} + +/// `GET /api/v1/werkbank/artifacts/{hash}?tenant=…` — serve a content-addressed +/// blob (the program a runner needs to load) **from the caller's own tenant +/// store**. +/// +/// Blobs are addressed by hash, and the hash is in the job record, so a store +/// shared across tenants let any valid runner key fetch any tenant's program +/// source. The read is now bound to the tenant the key is bound to +/// ([`RunnerTenant`]); another tenant's blob is simply absent from that subtree +/// and the request 404s. The hash itself is still validated against traversal by +/// [`crate::ingest::blob::read_tenant_blob`]. #[tracing::instrument(skip_all, fields(hash = %hash))] pub async fn serve_artifact( Extension(agent): AgentExt, + bound: Option>, Path(hash): Path, + Query(q): Query, ) -> Result { + let tenant = match (&bound, q.tenant.as_deref()) { + // A named tenant must be the one the key is bound to. + (_, Some(requested)) => { + ensure_tenant(&bound, requested)?; + requested.to_string() + } + (Some(Extension(RunnerTenant(t))), None) => t.clone(), + // Static runner token and no `?tenant=`: there is nothing to scope the + // read to, and an unscoped read is the bug being fixed. + (None, None) => { + tracing::warn!("artifact fetch without a tenant"); + return Err(StatusCode::BAD_REQUEST); + } + }; let base = std::path::Path::new(&agent.config.artifact_store_base_path); - match crate::ingest::blob::read_blob(base, &hash) { + match crate::ingest::blob::read_tenant_blob(base, &tenant, &hash) { Ok(bytes) => { Ok(([(header::CONTENT_TYPE, "application/octet-stream")], bytes).into_response()) } @@ -236,7 +294,7 @@ pub async fn enqueue( // Extract the control-logic program from the target's PLC-source artifacts // (same selection as the in-process PLC scan). - let ctx = crate::ingest::IngestContext::from_config(&agent.config, &req.target_id); + let ctx = crate::ingest::IngestContext::from_config(&agent.config, &req.tenant, &req.target_id); let ingest_set = crate::ingest::ingest_all(&target, &ctx).map_err(internal)?; let program = target .artifacts @@ -255,10 +313,12 @@ pub async fn enqueue( }) .ok_or(StatusCode::UNPROCESSABLE_ENTITY)?; - // Stash the program source so the runner can fetch it by hash. + // Stash the program source in this tenant's store so its runner — and only + // its runner — can fetch it by hash. let base = std::path::Path::new(&agent.config.artifact_store_base_path); let hash = - crate::ingest::blob::store_bytes(base, program.source.as_bytes()).map_err(internal)?; + crate::ingest::blob::store_tenant_bytes(base, &req.tenant, program.source.as_bytes()) + .map_err(internal)?; let job_id = format!("job_{}", uuid::Uuid::new_v4().simple()); let job = Job::plc_provision( @@ -334,7 +394,11 @@ fn constant_time_eq(a: &str, b: &str) -> bool { #[cfg(test)] mod tests { - use super::constant_time_eq; + use super::{constant_time_eq, runner_key_accepted, RUNNER_SCOPE}; + + fn scopes(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() + } #[test] fn token_compare() { @@ -343,4 +407,31 @@ mod tests { assert!(!constant_time_eq("secret", "secretx")); assert!(!constant_time_eq("", "x")); } + + #[test] + fn a_key_with_the_runner_scope_is_accepted() { + assert!(runner_key_accepted(true, &scopes([RUNNER_SCOPE].as_ref()))); + assert!(runner_key_accepted( + true, + &scopes(&["scan:read", RUNNER_SCOPE]) + )); + } + + /// The regression this guards: a key issued for this product but with no + /// runner scope (a dashboard or reporting key) used to pass, because the + /// check accepted `scope OR product == pruefwerk`. + #[test] + fn a_pruefwerk_key_without_the_runner_scope_is_rejected() { + assert!(!runner_key_accepted(true, &scopes(&["scan:read"]))); + assert!(!runner_key_accepted(true, &scopes(&["werkbank:admin"]))); + assert!(!runner_key_accepted(true, &[])); + } + + #[test] + fn an_invalid_key_is_rejected_even_with_the_scope() { + assert!(!runner_key_accepted( + false, + &scopes([RUNNER_SCOPE].as_ref()) + )); + } } diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index d544489..ba38d4b 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -8,10 +8,6 @@ pub fn build_router() -> Router { .route("/api/v1/health", get(handlers::health)) .route("/api/v1/oscal/assess", post(handlers::oscal::assess_target)) .route("/api/v1/stats/overview", get(handlers::stats_overview)) - .route( - "/api/v1/settings/ssh-public-key", - get(handlers::get_ssh_public_key), - ) // Unified onboarding targets (#131). .route( "/api/v1/targets", diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 7a7ecef..1fd1355 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -62,8 +62,6 @@ fn build_config(app_env: AppEnv) -> Result { .unwrap_or_else(|| "/tmp/compliance-scanner/repos".to_string()), artifact_store_base_path: env_var_opt("ARTIFACT_STORE_BASE_PATH") .unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()), - ssh_key_path: env_var_opt("SSH_KEY_PATH") - .unwrap_or_else(|| "/data/compliance-scanner/ssh/id_ed25519".to_string()), keycloak_url: env_var_opt("KEYCLOAK_URL"), keycloak_realm: env_var_opt("KEYCLOAK_REALM"), keycloak_admin_username: env_var_opt("KEYCLOAK_ADMIN_USERNAME"), diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 4b50f36..669f0ff 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -107,6 +107,22 @@ impl DatabasePool { Ok(db) } + /// A read-only handle to a tenant database **without** creating anything. + /// + /// [`Self::for_tenant_id`] ensures indexes, and `createIndex` materializes + /// the database and its collections. On an authenticated path that is what + /// you want; on an unauthenticated one it is a write primitive: a webhook + /// POST naming any `tenant_id` conjured `_` and its + /// indexes before anything checked the tenant existed. Reads through this + /// handle create nothing — a lookup in an unknown tenant simply finds + /// nothing, which the caller turns into a 404. + /// + /// Use it for the lookup that *establishes* the caller's right to be here; + /// switch to [`Self::for_tenant_id`] once that has succeeded. + pub fn for_existing_tenant_id(&self, tenant_id: &str) -> Database { + Database::from_database(self.client.database(&self.tenant_db_name(tenant_id))) + } + /// Compute the Mongo database name for a tenant. Public for tests /// and tenant offboarding (`pool.client().database(name).drop()`). /// diff --git a/compliance-agent/src/ingest/blob.rs b/compliance-agent/src/ingest/blob.rs index fb90972..64cebae 100644 --- a/compliance-agent/src/ingest/blob.rs +++ b/compliance-agent/src/ingest/blob.rs @@ -32,12 +32,26 @@ pub fn hash_file(path: &Path) -> Result<(String, u64), AgentError> { Ok((hex::encode(hasher.finalize()), total)) } -/// Store raw bytes in the content-addressed blob store under `base`, returning -/// the SHA-256 digest. Used to stash a small derived artifact (e.g. the extracted +/// The root of one tenant's runner-artifact store: +/// `/tenants//blobs`. +/// +/// Runner artifacts are addressed by content hash, and a hash is guessable from +/// the job record — so a store shared across tenants means any authenticated +/// runner can fetch any tenant's program source. Giving each tenant its own +/// subtree makes that structurally impossible: the path a request can reach is +/// fixed by the tenant its key is bound to, not by the hash it asks for. +fn tenant_blob_root(base: &Path, tenant: &str) -> PathBuf { + base.join("tenants") + .join(crate::tenant_path::tenant_segment(tenant)) + .join("blobs") +} + +/// Store raw bytes in `tenant`'s content-addressed blob store, returning the +/// SHA-256 digest. Used to stash a small derived artifact (e.g. the extracted /// PLC program source) so a Werkbank runner can fetch it by hash. Idempotent. -pub fn store_bytes(base: &Path, bytes: &[u8]) -> Result { +pub fn store_tenant_bytes(base: &Path, tenant: &str, bytes: &[u8]) -> Result { let sha = hex::encode(Sha256::digest(bytes)); - let dir = base.join("blobs").join(&sha[0..2]); + let dir = tenant_blob_root(base, tenant).join(&sha[0..2]); fs::create_dir_all(&dir)?; let dest = dir.join(&sha); if !dest.exists() { @@ -46,13 +60,14 @@ pub fn store_bytes(base: &Path, bytes: &[u8]) -> Result { Ok(sha) } -/// Read a blob's bytes by its SHA-256 digest. Rejects a non-hex/wrong-length hash -/// so a request can't traverse outside the blob store. -pub fn read_blob(base: &Path, sha: &str) -> Result, AgentError> { +/// Read a blob's bytes from `tenant`'s store by SHA-256 digest. Rejects a +/// non-hex/wrong-length hash so a request can't traverse outside the store, and +/// a digest another tenant stored is simply not there (`NotFound`). +pub fn read_tenant_blob(base: &Path, tenant: &str, sha: &str) -> Result, AgentError> { if sha.len() != 64 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) { return Err(AgentError::Other(format!("invalid content hash '{sha}'"))); } - let path = base.join("blobs").join(&sha[0..2]).join(sha); + let path = tenant_blob_root(base, tenant).join(&sha[0..2]).join(sha); Ok(fs::read(path)?) } @@ -156,6 +171,44 @@ mod tests { assert_eq!(fs::read(&p1).expect("read"), b"payload"); } + #[test] + fn a_tenants_blob_is_invisible_to_another_tenant() { + let base = Scratch::new(); + let sha = store_tenant_bytes(base.path(), "tenant-a", b"tenant-a program").expect("store"); + + // The owning tenant reads it back. + assert_eq!( + read_tenant_blob(base.path(), "tenant-a", &sha).expect("own blob"), + b"tenant-a program" + ); + // Another tenant asking for the very same digest gets nothing. + assert!( + read_tenant_blob(base.path(), "tenant-b", &sha).is_err(), + "tenant-b must not read tenant-a's blob" + ); + // Identical content stored by another tenant is a separate file. + let sha_b = + store_tenant_bytes(base.path(), "tenant-b", b"tenant-a program").expect("store"); + assert_eq!(sha, sha_b, "content addressing is unchanged"); + assert!(read_tenant_blob(base.path(), "tenant-b", &sha).is_ok()); + } + + #[test] + fn tenant_blob_rejects_a_non_hash_and_cannot_traverse() { + let base = Scratch::new(); + for bad in ["..", "../../etc/passwd", "short", ""] { + assert!( + read_tenant_blob(base.path(), "t", bad).is_err(), + "{bad} should not be a valid content hash" + ); + } + // A traversal attempt in the tenant id stays under the store root. + let sha = store_tenant_bytes(base.path(), "../../escape", b"x").expect("store"); + let root = base.path().join("tenants"); + assert!(root.exists(), "store must stay under /tenants"); + assert!(read_tenant_blob(base.path(), "../../escape", &sha).is_ok()); + } + #[test] fn extract_zip_writes_entries() { let base = Scratch::new(); diff --git a/compliance-agent/src/ingest/mod.rs b/compliance-agent/src/ingest/mod.rs index 61ca72d..b76ea78 100644 --- a/compliance-agent/src/ingest/mod.rs +++ b/compliance-agent/src/ingest/mod.rs @@ -24,8 +24,9 @@ pub struct IngestContext<'a> { pub artifact_store_base: &'a Path, /// Base directory for git clones. pub git_clone_base: &'a str, - /// Default SSH key path (used when an artifact provides none). - pub ssh_key_path: &'a str, + /// The tenant these artifacts belong to. Namespaces the git clone directory + /// so two tenants never share a checkout. + pub tenant_id: &'a str, /// The id of the target these artifacts belong to (namespaces working dirs). pub target_id: &'a str, /// Where this deployment may fetch from (SSRF policy, #256). @@ -33,12 +34,12 @@ pub struct IngestContext<'a> { } impl<'a> IngestContext<'a> { - /// Build an ingest context from the agent config for a given target. - pub fn from_config(config: &'a AgentConfig, target_id: &'a str) -> Self { + /// Build an ingest context from the agent config for a given tenant's target. + pub fn from_config(config: &'a AgentConfig, tenant_id: &'a str, target_id: &'a str) -> Self { Self { artifact_store_base: Path::new(&config.artifact_store_base_path), git_clone_base: &config.git_clone_base_path, - ssh_key_path: &config.ssh_key_path, + tenant_id, target_id, net_guard: NetGuard::from_env(config.app_env), } @@ -144,8 +145,8 @@ fn ingest_git( ctx.net_guard .check_git_url(&artifact.source_ref) .map_err(|e| AgentError::Other(e.to_string()))?; - let creds = credentials_for(artifact, ctx.ssh_key_path); - let git_ops = GitOps::new(ctx.git_clone_base, creds); + let creds = credentials_for(artifact); + let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds); let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?; let head = GitOps::get_head_sha(&repo_path).ok(); Ok(IngestedArtifact { @@ -274,13 +275,13 @@ fn local_source(artifact: &Artifact) -> Result { Ok(path) } -/// Build git credentials from an artifact's auth plus a default SSH key path. -fn credentials_for(artifact: &Artifact, default_ssh_key_path: &str) -> RepoCredentials { +/// Build git credentials from an artifact's own auth. HTTPS token only: there +/// is no agent-wide SSH key to fall back to any more, because one shared key +/// authenticated every tenant's clone (see +/// [`crate::pipeline::git::reject_ssh_url`]). +fn credentials_for(artifact: &Artifact) -> RepoCredentials { let auth = artifact.auth.as_ref(); RepoCredentials { - ssh_key_path: auth - .and_then(|a| a.ssh_key_path.clone()) - .or_else(|| Some(default_ssh_key_path.to_string())), auth_token: auth.and_then(|a| a.secret.clone()), auth_username: auth.and_then(|a| a.username.clone()), } @@ -311,7 +312,7 @@ mod tests { IngestContext { artifact_store_base: store, git_clone_base: "/tmp/cs-ingest-test-repos", - ssh_key_path: "/tmp/cs-ingest-test-ssh", + tenant_id: "test-tenant", target_id, net_guard: NetGuard::public_only(), } @@ -441,17 +442,20 @@ mod tests { secret: Some("pat".to_string()), ..Default::default() }); - let creds = credentials_for(&artifact, "/default/ssh/key"); + let creds = credentials_for(&artifact); assert_eq!(creds.auth_token.as_deref(), Some("pat")); assert_eq!(creds.auth_username.as_deref(), Some("bob")); } + /// No agent-wide credential is invented for an artifact that carries none: + /// the shared SSH deploy key that used to fill this in belonged to every + /// tenant at once. #[test] - fn credentials_fall_back_to_default_ssh_key() { - let artifact = Artifact::git_repo("git@host:x.git", "main"); - let creds = credentials_for(&artifact, "/default/ssh/key"); - assert_eq!(creds.ssh_key_path.as_deref(), Some("/default/ssh/key")); + fn credentials_are_empty_without_artifact_auth() { + let artifact = Artifact::git_repo("https://host/x.git", "main"); + let creds = credentials_for(&artifact); assert!(creds.auth_token.is_none()); + assert!(creds.auth_username.is_none()); } /// A single uploaded PLC file (not an archive) must land in a working dir diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 9162361..c4cf63e 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -16,8 +16,8 @@ pub mod pipeline; pub mod rag; pub mod registry; pub mod scheduler; -pub mod ssh; pub mod targets; +pub mod tenant_path; #[allow(dead_code)] pub mod trackers; pub mod webhooks; diff --git a/compliance-agent/src/main.rs b/compliance-agent/src/main.rs index 110634f..0d8a729 100644 --- a/compliance-agent/src/main.rs +++ b/compliance-agent/src/main.rs @@ -1,4 +1,4 @@ -use compliance_agent::{agent, api, config, database, scheduler, ssh, webhooks}; +use compliance_agent::{agent, api, config, database, scheduler, webhooks}; #[tokio::main] async fn main() -> Result<(), Box> { @@ -18,12 +18,6 @@ async fn main() -> Result<(), Box> { ); let config = config::load_config()?; - // Ensure SSH key pair exists for cloning private repos - match ssh::ensure_ssh_key(&config.ssh_key_path) { - Ok(pubkey) => tracing::info!("SSH public key: {}", pubkey.trim()), - Err(e) => tracing::warn!("SSH key generation skipped: {e}"), - } - tracing::info!("Connecting to MongoDB..."); // Per-tenant pool only — the agent has no shared "default" database // after M7.2-D. `mongodb_database` is now the db-name prefix used diff --git a/compliance-agent/src/pipeline/git.rs b/compliance-agent/src/pipeline/git.rs index f29d5e0..440cad2 100644 --- a/compliance-agent/src/pipeline/git.rs +++ b/compliance-agent/src/pipeline/git.rs @@ -3,12 +3,54 @@ use std::path::{Path, PathBuf}; use git2::{Cred, FetchOptions, RemoteCallbacks, Repository}; use crate::error::AgentError; +use crate::tenant_path::{name_segment, tenant_segment}; -/// Credentials for accessing a private repository +/// The directory a tenant's checkout of `repo_name` lives in. +/// +/// **The single clone-path convention.** Every producer and every consumer of a +/// checkout path goes through here — the orchestrator, PR review, ingest, the +/// graph build, the chat embedding build and the file-content reader. A second +/// convention is how two tenants end up sharing one checkout: before this, both +/// resolved to `/`, so the second tenant to scan a target with the +/// same name fetched the first tenant's `origin` instead of cloning its own. +/// +/// Both segments are collapsed to one safe path component, so traversal in +/// either the tenant id or the target name cannot escape `base`. +pub fn clone_dir(base: &Path, tenant_id: &str, repo_name: &str) -> PathBuf { + base.join(tenant_segment(tenant_id)) + .join(name_segment(repo_name)) +} + +/// Reject a git URL that would authenticate with an SSH key. +/// +/// At MVP the agent holds no git SSH key at all: it used to authenticate every +/// tenant's clone with one shared deploy key, which is a cross-tenant read +/// primitive (tenant A adds the agent's key to a repo, tenant B names that repo +/// and the agent happily clones it). Per-tenant key management is R1; until +/// then git access is HTTPS-with-a-token only, and an SSH URL fails loudly +/// rather than silently borrowing somebody else's credential. +pub fn reject_ssh_url(git_url: &str) -> Result<(), AgentError> { + let url = git_url.trim(); + let is_ssh = url.starts_with("ssh://") + || url.starts_with("git+ssh://") + // scp-style `git@host:org/repo.git` (no scheme, user before a `:`). + || url + .split_once('@') + .is_some_and(|(user, rest)| !user.contains("://") && rest.contains(':')); + if is_ssh { + return Err(AgentError::Other(format!( + "SSH git URLs are not supported: '{git_url}'. Use an HTTPS clone URL \ + (https://host/org/repo.git) with a personal access token or deploy \ + token in the target's credentials." + ))); + } + Ok(()) +} + +/// Credentials for accessing a private repository. HTTPS token only — see +/// [`reject_ssh_url`]. #[derive(Debug, Clone, Default)] pub struct RepoCredentials { - /// Path to the SSH private key (for SSH URLs) - pub ssh_key_path: Option, /// Auth token / password (for HTTPS URLs) pub auth_token: Option, /// Username for HTTPS auth (defaults to "x-access-token") @@ -18,23 +60,12 @@ pub struct RepoCredentials { impl RepoCredentials { pub(crate) fn make_callbacks(&self) -> RemoteCallbacks<'_> { let mut callbacks = RemoteCallbacks::new(); - let ssh_key = self.ssh_key_path.clone(); let token = self.auth_token.clone(); let username = self.auth_username.clone(); - callbacks.credentials(move |_url, username_from_url, allowed_types| { - // SSH key authentication - if allowed_types.contains(git2::CredentialType::SSH_KEY) { - if let Some(ref key_path) = ssh_key { - let key = Path::new(key_path); - if key.exists() { - let user = username_from_url.unwrap_or("git"); - return Cred::ssh_key(user, None, key, None); - } - } - } - - // HTTPS userpass authentication + callbacks.credentials(move |_url, _username_from_url, allowed_types| { + // HTTPS userpass authentication. There is deliberately no SSH branch: + // the agent has no key to offer. if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) { if let Some(ref tok) = token { let user = username.as_deref().unwrap_or("x-access-token"); @@ -57,33 +88,36 @@ impl RepoCredentials { } fn has_credentials(&self) -> bool { - self.ssh_key_path - .as_ref() - .map(|p| Path::new(p).exists()) - .unwrap_or(false) - || self.auth_token.is_some() + self.auth_token.is_some() } } pub struct GitOps { base_path: PathBuf, + /// The tenant every checkout this instance makes belongs to. + tenant_id: String, credentials: RepoCredentials, } impl GitOps { - pub fn new(base_path: &str, credentials: RepoCredentials) -> Self { + pub fn new(base_path: &str, tenant_id: &str, credentials: RepoCredentials) -> Self { Self { base_path: PathBuf::from(base_path), + tenant_id: tenant_id.to_string(), credentials, } } - #[tracing::instrument(skip_all, fields(repo_name = %repo_name))] + /// Where this instance's tenant keeps its checkout of `repo_name`. + pub fn clone_path(&self, repo_name: &str) -> PathBuf { + clone_dir(&self.base_path, &self.tenant_id, repo_name) + } + + #[tracing::instrument(skip_all, fields(tenant = %self.tenant_id, repo_name = %repo_name))] pub fn clone_or_fetch(&self, git_url: &str, repo_name: &str) -> Result { - // Names can contain slashes or other path-hostile characters (a target - // named after a repo path, say); collapse to one safe directory segment - // so the clone path never nests or breaks. - let repo_path = self.base_path.join(sanitize_repo_dir(repo_name)); + reject_ssh_url(git_url)?; + // Per tenant: two tenants with the same target name get two checkouts. + let repo_path = self.clone_path(repo_name); if repo_path.exists() { tracing::info!("fetching updates for existing repo"); @@ -128,6 +162,7 @@ impl GitOps { /// Test that we can access a remote repository (used during add validation) pub fn test_access(git_url: &str, credentials: &RepoCredentials) -> Result<(), AgentError> { + reject_ssh_url(git_url)?; let mut remote = git2::Remote::create_detached(git_url)?; let callbacks = credentials.make_callbacks(); remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)?; @@ -135,13 +170,10 @@ impl GitOps { Ok(()) } - /// Build credentials from agent config + per-repo overrides - pub fn make_repo_credentials( - config: &compliance_core::AgentConfig, - repo: &crate::pipeline::repo_view::RepoView, - ) -> RepoCredentials { + /// Build credentials from a repo view's own HTTPS token. There is no + /// agent-wide fallback credential any more — see [`reject_ssh_url`]. + pub fn make_repo_credentials(repo: &crate::pipeline::repo_view::RepoView) -> RepoCredentials { RepoCredentials { - ssh_key_path: Some(config.ssh_key_path.clone()), auth_token: repo.auth_token.clone(), auth_username: repo.auth_username.clone(), } @@ -257,45 +289,85 @@ pub struct DiffFile { pub hunks: String, } -/// Collapse a repository name into a single filesystem-safe directory segment. -/// Names may carry slashes or other path-hostile characters (a target named -/// after a repo path, for instance); those would otherwise nest or break the -/// clone path, so map anything outside `[A-Za-z0-9._-]` to `_`. -fn sanitize_repo_dir(name: &str) -> String { - let mapped: String = name - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' { - c - } else { - '_' - } - }) - .collect(); - let trimmed = mapped.trim_matches(|c| c == '.' || c == '_'); - if trimmed.is_empty() { - "repo".to_string() - } else { - trimmed.to_string() - } -} - #[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { - use super::sanitize_repo_dir; + use super::{clone_dir, reject_ssh_url}; + use std::path::Path; + + const BASE: &str = "/data/repos"; #[test] - fn sanitizes_path_hostile_names() { + fn same_target_name_in_two_tenants_gets_two_directories() { + let a = clone_dir(Path::new(BASE), "tenant-a", "acme-firmware"); + let b = clone_dir(Path::new(BASE), "tenant-b", "acme-firmware"); + assert_ne!(a, b, "two tenants must not share a checkout"); + assert_eq!(a, Path::new("/data/repos/tenant-a/acme-firmware")); + assert_eq!(b, Path::new("/data/repos/tenant-b/acme-firmware")); + } + + #[test] + fn clone_dir_is_stable_for_the_same_tenant_and_name() { assert_eq!( - sanitize_repo_dir("zephyr-example-app"), - "zephyr-example-app" + clone_dir(Path::new(BASE), "t1", "repo"), + clone_dir(Path::new(BASE), "t1", "repo") ); + } + + #[test] + fn clone_dir_sanitises_traversal_in_the_target_name() { + let p = clone_dir(Path::new(BASE), "t1", "../../etc/passwd"); + assert_eq!(p, Path::new("/data/repos/t1/etc_passwd")); + assert!(p.starts_with("/data/repos/t1")); assert_eq!( - sanitize_repo_dir("ChristianRinn/bare_metal_stm32f411xe"), - "ChristianRinn_bare_metal_stm32f411xe" + clone_dir( + Path::new(BASE), + "t1", + "ChristianRinn/bare_metal_stm32f411xe" + ), + Path::new("/data/repos/t1/ChristianRinn_bare_metal_stm32f411xe") ); - assert_eq!(sanitize_repo_dir("../../etc/passwd"), "etc_passwd"); - assert_eq!(sanitize_repo_dir("a b:c"), "a_b_c"); - assert_eq!(sanitize_repo_dir("///"), "repo"); + } + + #[test] + fn clone_dir_sanitises_traversal_in_the_tenant_id() { + let p = clone_dir(Path::new(BASE), "../../../etc", "repo"); + assert!( + p.starts_with("/data/repos"), + "{} escaped the clone base", + p.display() + ); + // Exactly base + two components: nothing nested, nothing climbed. + assert_eq!( + p.components().count(), + Path::new(BASE).components().count() + 2 + ); + } + + #[test] + fn ssh_urls_are_rejected_with_an_https_hint() { + for url in [ + "ssh://git@github.com/org/repo.git", + "git@github.com:org/repo.git", + "git+ssh://git@git.example.com/org/repo.git", + " git@gitlab.com:org/repo.git ", + ] { + let msg = match reject_ssh_url(url) { + Err(e) => e.to_string(), + Ok(()) => panic!("{url} should be rejected"), + }; + assert!(msg.contains("HTTPS"), "{url}: {msg}"); + } + } + + #[test] + fn https_urls_are_accepted() { + for url in [ + "https://github.com/org/repo.git", + "https://x-access-token:tok@github.com/org/repo.git", + "http://internal.example.com/org/repo.git", + ] { + assert!(reject_ssh_url(url).is_ok(), "{url} should be accepted"); + } } } diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 670e5e5..35a5ac4 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -32,6 +32,10 @@ pub struct GraphContext { pub struct PipelineOrchestrator { pub(super) config: AgentConfig, + /// The tenant this run belongs to. Carried explicitly because the on-disk + /// paths a scan touches (git checkouts, working dirs) are per tenant — the + /// [`Database`] handle alone isolates Mongo, not the filesystem. + pub(super) tenant_id: String, pub(super) db: Database, pub(super) llm: Arc, pub(super) http: reqwest::Client, @@ -40,12 +44,14 @@ pub struct PipelineOrchestrator { impl PipelineOrchestrator { pub fn new( config: AgentConfig, + tenant_id: &str, db: Database, llm: Arc, http: reqwest::Client, ) -> Self { Self { config, + tenant_id: tenant_id.to_string(), db, llm, http, @@ -58,8 +64,8 @@ impl PipelineOrchestrator { // Stage 0: Change detection tracing::info!("[{repo_id}] Stage 0: Change detection"); - let creds = GitOps::make_repo_credentials(&self.config, repo); - let git_ops = GitOps::new(&self.config.git_clone_base_path, creds); + let creds = GitOps::make_repo_credentials(repo); + let git_ops = GitOps::new(&self.config.git_clone_base_path, &self.tenant_id, creds); let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.name)?; if !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())? { @@ -559,7 +565,8 @@ impl PipelineOrchestrator { tracing::info!(target_id, "[{target_id}] PLC control-logic analysis"); self.update_phase(scan_run_id, "plc_analysis").await; - let ctx = crate::ingest::IngestContext::from_config(&self.config, target_id); + let ctx = + crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id); let ingest_set = crate::ingest::ingest_all(target, &ctx)?; // Every PLC-source artifact on the target: dedicated PLC projects plus any // code artifacts (git repo / source archive) holding PLCopen XML / ST @@ -696,7 +703,8 @@ impl PipelineOrchestrator { // Locate a loadable control-logic program among the PLC-source artifacts // (same selection as the static PLC scan: dedicated PLC projects plus code // artifacts holding PLCopen XML / ST exports). - let ctx = crate::ingest::IngestContext::from_config(&self.config, target_id); + let ctx = + crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id); let ingest_set = crate::ingest::ingest_all(target, &ctx)?; let program = target .artifacts @@ -973,7 +981,8 @@ impl PipelineOrchestrator { scan_run_id: &str, ) { self.update_phase(scan_run_id, "classification").await; - let ctx = crate::ingest::IngestContext::from_config(&self.config, target_id); + let ctx = + crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id); let ingest_set = match crate::ingest::ingest_all(target, &ctx) { Ok(set) => set, Err(e) => { @@ -1131,7 +1140,11 @@ impl PipelineOrchestrator { ) .await?; - let repo_path = std::path::Path::new(&self.config.git_clone_base_path).join(&repo.name); + let repo_path = crate::pipeline::git::clone_dir( + std::path::Path::new(&self.config.git_clone_base_path), + &self.tenant_id, + &repo.name, + ); if let (Ok(sha), Some(code)) = (GitOps::get_head_sha(&repo_path), target.code_artifact()) { self.db .onboarded_targets() diff --git a/compliance-agent/src/pipeline/pr_review.rs b/compliance-agent/src/pipeline/pr_review.rs index c3ea5d7..9614e78 100644 --- a/compliance-agent/src/pipeline/pr_review.rs +++ b/compliance-agent/src/pipeline/pr_review.rs @@ -36,8 +36,8 @@ impl PipelineOrchestrator { } // Clone/fetch the repo - let creds = GitOps::make_repo_credentials(&self.config, repo); - let git_ops = GitOps::new(&self.config.git_clone_base_path, creds); + let creds = GitOps::make_repo_credentials(repo); + let git_ops = GitOps::new(&self.config.git_clone_base_path, &self.tenant_id, creds); let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.name)?; // Get diff between base and head diff --git a/compliance-agent/src/ssh.rs b/compliance-agent/src/ssh.rs deleted file mode 100644 index 772a0c0..0000000 --- a/compliance-agent/src/ssh.rs +++ /dev/null @@ -1,53 +0,0 @@ -use std::path::Path; - -use crate::error::AgentError; - -/// Ensure the SSH key pair exists at the given path, generating it if missing. -/// Returns the public key contents. -pub fn ensure_ssh_key(key_path: &str) -> Result { - let private_path = Path::new(key_path); - let public_path = private_path.with_extension("pub"); - - if private_path.exists() && public_path.exists() { - return std::fs::read_to_string(&public_path) - .map_err(|e| AgentError::Config(format!("Failed to read SSH public key: {e}"))); - } - - // Create parent directory - if let Some(parent) = private_path.parent() { - std::fs::create_dir_all(parent)?; - } - - // Generate ed25519 key pair using ssh-keygen - let output = std::process::Command::new("ssh-keygen") - .args([ - "-t", - "ed25519", - "-f", - key_path, - "-N", - "", // no passphrase - "-C", - "compliance-scanner-agent", - ]) - .output() - .map_err(|e| AgentError::Config(format!("Failed to run ssh-keygen: {e}")))?; - - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - return Err(AgentError::Config(format!("ssh-keygen failed: {stderr}"))); - } - - // Set correct permissions - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(private_path, std::fs::Permissions::from_mode(0o600))?; - } - - let public_key = std::fs::read_to_string(&public_path) - .map_err(|e| AgentError::Config(format!("Failed to read generated SSH public key: {e}")))?; - - tracing::info!("Generated new SSH key pair at {key_path}"); - Ok(public_key) -} diff --git a/compliance-agent/src/tenant_path.rs b/compliance-agent/src/tenant_path.rs new file mode 100644 index 0000000..182ac3f --- /dev/null +++ b/compliance-agent/src/tenant_path.rs @@ -0,0 +1,120 @@ +//! Filesystem path segments that carry a tenant boundary. +//! +//! Everything the agent writes for a target — git clones, werkbank artifact +//! blobs — lives under a directory named after the owning tenant. Two tenants +//! that onboard a target with the same name, or a blob with the same digest, +//! must never land on the same path: that is how one tenant ends up fetching +//! into (or reading out of) another tenant's checkout. +//! +//! Both segment builders here collapse their input to a single safe path +//! component, so a `..` or a `/` in a tenant id or a target name can never +//! escape or nest. [`tenant_segment`] additionally keeps the mapping +//! *injective*, which [`name_segment`] does not need to be. + +use sha2::{Digest, Sha256}; + +/// Characters that survive into a path segment verbatim. +fn is_safe(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' +} + +/// Map anything outside `[A-Za-z0-9._-]` to `_` and trim leading/trailing +/// `.`/`_`, so the result is one path component and never `.`/`..`. +fn collapse(raw: &str) -> String { + let mapped: String = raw + .chars() + .map(|c| if is_safe(c) { c } else { '_' }) + .collect(); + mapped.trim_matches(|c| c == '.' || c == '_').to_string() +} + +/// The directory segment for a **tenant**. +/// +/// Collapsing is lossy — `a/b`, `a:b` and `a_b` all map to `a_b` — and for a +/// tenant that would be a shared directory, i.e. exactly the isolation bug this +/// exists to prevent. So whenever collapsing changed anything (or emptied the +/// input), a digest of the *raw* id is appended: distinct tenant ids then always +/// get distinct directories. Well-formed ids (UUIDs, slugs) are unchanged and +/// stay readable. +pub fn tenant_segment(tenant_id: &str) -> String { + let collapsed = collapse(tenant_id); + if !collapsed.is_empty() && collapsed == tenant_id { + return collapsed; + } + let digest = hex::encode(Sha256::digest(tenant_id.as_bytes())); + let stem = if collapsed.is_empty() { + "t" + } else { + &collapsed + }; + format!("{stem}-{}", &digest[..16]) +} + +/// The directory segment for a **name inside a tenant** (a target/repo name). +/// +/// Names can carry slashes or other path-hostile characters (a target named +/// after a repo path, say); those would otherwise nest or break the path. Only +/// collision-free *across* tenants — which the enclosing [`tenant_segment`] +/// guarantees. +pub fn name_segment(name: &str) -> String { + let collapsed = collapse(name); + if collapsed.is_empty() { + "repo".to_string() + } else { + collapsed + } +} + +#[cfg(test)] +mod tests { + use super::{name_segment, tenant_segment}; + + #[test] + fn name_segment_collapses_path_hostile_names() { + assert_eq!(name_segment("zephyr-example-app"), "zephyr-example-app"); + assert_eq!( + name_segment("ChristianRinn/bare_metal_stm32f411xe"), + "ChristianRinn_bare_metal_stm32f411xe" + ); + assert_eq!(name_segment("../../etc/passwd"), "etc_passwd"); + assert_eq!(name_segment("a b:c"), "a_b_c"); + assert_eq!(name_segment("///"), "repo"); + } + + #[test] + fn tenant_segment_passes_well_formed_ids_through() { + assert_eq!( + tenant_segment("3f2b9c1e-0a5d-4c88-9f1a-7b2c3d4e5f60"), + "3f2b9c1e-0a5d-4c88-9f1a-7b2c3d4e5f60" + ); + assert_eq!(tenant_segment("acme_gmbh"), "acme_gmbh"); + } + + #[test] + fn tenant_segment_sanitises_traversal() { + let seg = tenant_segment("../../etc"); + assert!(!seg.contains('/'), "{seg} must be one path component"); + assert!(!seg.contains(".."), "{seg} must not traverse"); + assert!(seg.starts_with("etc-"), "{seg}"); + } + + #[test] + fn tenant_segment_is_injective_where_collapsing_is_not() { + // These three collapse to the same string; they must not share a dir. + let a = tenant_segment("acme/eu"); + let b = tenant_segment("acme:eu"); + let c = tenant_segment("acme_eu"); + assert_ne!(a, b); + assert_ne!(a, c); + assert_ne!(b, c); + // …and an id that needs no collapsing is left alone. + assert_eq!(c, "acme_eu"); + } + + #[test] + fn tenant_segment_never_empty() { + assert!(!tenant_segment("").is_empty()); + assert!(!tenant_segment("///").is_empty()); + assert_ne!(tenant_segment(""), tenant_segment("///")); + } +} diff --git a/compliance-agent/src/webhooks/gitea.rs b/compliance-agent/src/webhooks/gitea.rs index 375b74c..3f86b1e 100644 --- a/compliance-agent/src/webhooks/gitea.rs +++ b/compliance-agent/src/webhooks/gitea.rs @@ -23,13 +23,10 @@ pub async fn handle_gitea_webhook( Ok(oid) => oid, Err(_) => return StatusCode::NOT_FOUND, }; - let db = match agent.db_pool.for_tenant_id(&tenant_id).await { - Ok(db) => db, - Err(e) => { - tracing::warn!("Gitea webhook: cannot open tenant database '{tenant_id}': {e}"); - return StatusCode::NOT_FOUND; - } - }; + // Unauthenticated so far: the signature is only verified once we have the + // repo's secret. Look the target up through a handle that creates nothing, + // so a POST with a made-up tenant id cannot conjure a database. + let db = agent.db_pool.for_existing_tenant_id(&tenant_id); let repo = match db .onboarded_targets() .find_one(mongodb::bson::doc! { "_id": oid }) diff --git a/compliance-agent/src/webhooks/github.rs b/compliance-agent/src/webhooks/github.rs index f10ee12..4a50ecf 100644 --- a/compliance-agent/src/webhooks/github.rs +++ b/compliance-agent/src/webhooks/github.rs @@ -23,13 +23,10 @@ pub async fn handle_github_webhook( Ok(oid) => oid, Err(_) => return StatusCode::NOT_FOUND, }; - let db = match agent.db_pool.for_tenant_id(&tenant_id).await { - Ok(db) => db, - Err(e) => { - tracing::warn!("GitHub webhook: cannot open tenant database '{tenant_id}': {e}"); - return StatusCode::NOT_FOUND; - } - }; + // Unauthenticated so far: the signature is only verified once we have the + // repo's secret. Look the target up through a handle that creates nothing, + // so a POST with a made-up tenant id cannot conjure a database. + let db = agent.db_pool.for_existing_tenant_id(&tenant_id); let repo = match db .onboarded_targets() .find_one(mongodb::bson::doc! { "_id": oid }) diff --git a/compliance-agent/src/webhooks/gitlab.rs b/compliance-agent/src/webhooks/gitlab.rs index fd12ff9..010767c 100644 --- a/compliance-agent/src/webhooks/gitlab.rs +++ b/compliance-agent/src/webhooks/gitlab.rs @@ -19,13 +19,10 @@ pub async fn handle_gitlab_webhook( Ok(oid) => oid, Err(_) => return StatusCode::NOT_FOUND, }; - let db = match agent.db_pool.for_tenant_id(&tenant_id).await { - Ok(db) => db, - Err(e) => { - tracing::warn!("GitLab webhook: cannot open tenant database '{tenant_id}': {e}"); - return StatusCode::NOT_FOUND; - } - }; + // Unauthenticated so far: the token is only verified once we have the repo's + // secret. Look the target up through a handle that creates nothing, so a + // POST with a made-up tenant id cannot conjure a database. + let db = agent.db_pool.for_existing_tenant_id(&tenant_id); let repo = match db .onboarded_targets() .find_one(mongodb::bson::doc! { "_id": oid }) diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index d5ea3d9..56e0f02 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -31,7 +31,6 @@ pub fn dev_config(mongodb_uri: String, db_name: String) -> AgentConfig { cve_monitor_schedule: String::new(), git_clone_base_path: "/tmp/compliance-scanner-tests/repos".into(), artifact_store_base_path: "/tmp/compliance-scanner-tests/artifacts".into(), - ssh_key_path: "/tmp/compliance-scanner-tests/ssh/id_ed25519".into(), pentest_imap_tls: false, werkbank_runner_token: Some(SecretString::from(TEST_RUNNER_TOKEN.to_string())), // Unauthenticated dev: no Keycloak, no audience, no registry. diff --git a/compliance-agent/tests/tenant_isolation.rs b/compliance-agent/tests/tenant_isolation.rs index 7a32d5d..d9f0f12 100644 --- a/compliance-agent/tests/tenant_isolation.rs +++ b/compliance-agent/tests/tenant_isolation.rs @@ -123,6 +123,57 @@ async fn for_tenant_is_idempotent_index_creation() { pool.client().database(&db_name).drop().await.expect("drop"); } +/// The unauthenticated-webhook path: looking a target up for an unknown tenant +/// must create nothing. `for_tenant_id` ensures indexes, and `createIndex` +/// materializes the database — so a POST naming any `tenant_id` used to conjure +/// `_` before anything checked the tenant was real. +#[tokio::test] +async fn for_existing_tenant_does_not_create_a_database() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!("m72n_{}", short_id()); + let pool = DatabasePool::connect(&uri, &prefix).await.expect("connect"); + + let ghost = "00000000-0000-0000-0000-00000000ghost"; + let ghost_db_name = pool.tenant_db_name(ghost); + + // The lookup a webhook does before it has authenticated anything. + let found = pool + .for_existing_tenant_id(ghost) + .onboarded_targets() + .find_one(doc! { "name": "anything" }) + .await + .expect("read on an unknown tenant must not error"); + assert!(found.is_none(), "an unknown tenant has no targets"); + + let names = pool.list_tenant_db_names().await.expect("list tenants"); + assert!( + !names.contains(&ghost_db_name), + "unauthenticated lookup created {ghost_db_name}: {names:?}" + ); + + // Contrast: the authenticated path still provisions the tenant. + let db = pool.for_tenant_id(ghost).await.expect("provision"); + db.onboarded_targets() + .insert_one(fixture_repo( + "ghost-app", + "https://example.com/ghost/app.git", + )) + .await + .expect("insert"); + let names = pool.list_tenant_db_names().await.expect("list tenants"); + assert!( + names.contains(&ghost_db_name), + "{ghost_db_name} in {names:?}" + ); + + pool.client() + .database(&ghost_db_name) + .drop() + .await + .expect("drop"); +} + #[tokio::test] async fn tenant_db_name_sanitizes_unsafe_characters() { let uri = std::env::var("TEST_MONGODB_URI") diff --git a/compliance-agent/tests/werkbank_api.rs b/compliance-agent/tests/werkbank_api.rs index b382530..1fe1f27 100644 --- a/compliance-agent/tests/werkbank_api.rs +++ b/compliance-agent/tests/werkbank_api.rs @@ -26,6 +26,9 @@ use compliance_core::models::{ use common::{dev_config, TEST_RUNNER_TOKEN}; const TENANT: &str = "dev"; +/// Two tenants for the artifact-isolation test. +const VICTIM: &str = "tenant-victim"; +const ATTACKER: &str = "tenant-attacker"; /// A running werkbank API on a random port, or `None` if no Mongo. struct Harness { @@ -101,11 +104,29 @@ impl Harness { } r } + /// `GET /api/v1/werkbank/artifacts/{hash}`, optionally naming a tenant. + async fn get_artifact(&self, hash: &str, tenant: Option<&str>) -> reqwest::Response { + let mut url = format!("{}/api/v1/werkbank/artifacts/{hash}", self.base_url); + if let Some(t) = tenant { + url.push_str(&format!("?tenant={t}")); + } + self.client + .get(url) + .bearer_auth(TEST_RUNNER_TOKEN) + .send() + .await + .unwrap() + } + async fn cleanup(&self) { + self.cleanup_tenant(TENANT).await; + } + + async fn cleanup_tenant(&self, tenant: &str) { let _ = self .pool .client() - .database(&format!("{}_{TENANT}", self.db_name)) + .database(&format!("{}_{tenant}", self.db_name)) .drop() .await; } @@ -231,21 +252,100 @@ async fn enqueue_extracts_program_stores_a_blob_and_serves_it() { .expect("program blob"); // Serve the blob back and confirm it's the program source (what the runner - // would fetch). - let served = h - .client - .get(format!("{}/api/v1/werkbank/artifacts/{hash}", h.base_url)) - .bearer_auth(TEST_RUNNER_TOKEN) - .send() - .await - .unwrap(); + // would fetch) — from the owning tenant's store. + let served = h.get_artifact(&hash, Some(TENANT)).await; assert_eq!(served.status(), 200); assert!(served.text().await.unwrap().contains("CONFIGURATION")); + // The same digest asked for as another tenant is not there. Blobs are + // content-addressed and the hash is readable from the job record, so an + // unscoped store would hand one tenant's program source to any runner. + let other = h.get_artifact(&hash, Some("some-other-tenant")).await; + assert_eq!( + other.status(), + 404, + "another tenant must not read this blob" + ); + + // And a fetch that names no tenant at all has nothing to scope the read to. + let unscoped = h.get_artifact(&hash, None).await; + assert_eq!( + unscoped.status(), + 400, + "an artifact fetch must name a tenant" + ); + h.cleanup().await; let _ = std::fs::remove_dir_all(&dir); } +/// A blob stored for one tenant is invisible to another even when both tenants +/// enqueue byte-identical control logic — the digests match, the stores do not. +#[tokio::test] +async fn an_artifact_is_scoped_to_the_tenant_that_stored_it() { + let Some(h) = start().await else { return }; + + let dir = std::env::temp_dir().join(format!("wbq-iso-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let st = dir.join("main.st"); + std::fs::write( + &st, + "PROGRAM Main\nEND_PROGRAM\nCONFIGURATION C\n RESOURCE R\nEND_CONFIGURATION\n", + ) + .unwrap(); + + // Tenant "victim" onboards the program and enqueues a job for it. + let victim_db = h.pool.for_tenant_id(VICTIM).await.unwrap(); + let mut target = OnboardedTarget::new("plc".into(), TargetType::PlcSps); + let mut art = Artifact::plc_project("main.st", PlcFormat::StructuredText); + art.stored_path = Some(st.to_string_lossy().to_string()); + target.artifacts.push(art); + let ins = victim_db + .onboarded_targets() + .insert_one(&target) + .await + .unwrap(); + let target_id = ins.inserted_id.as_object_id().unwrap().to_hex(); + + let resp = h + .post( + "/api/v1/werkbank/jobs/enqueue", + Some(TEST_RUNNER_TOKEN), + serde_json::json!({ "tenant": VICTIM, "target_id": target_id }), + ) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 200); + let job_id = resp.json::().await.unwrap()["job_id"] + .as_str() + .unwrap() + .to_string(); + let hash = JobQueue::new(&victim_db) + .get(&job_id) + .await + .unwrap() + .unwrap() + .job + .inputs + .get("program") + .and_then(|i| i.blob.clone()) + .expect("program blob"); + + // The owner reads it; the attacker, holding an equally valid runner + // credential and the hash from the job record, does not. + assert_eq!(h.get_artifact(&hash, Some(VICTIM)).await.status(), 200); + assert_eq!( + h.get_artifact(&hash, Some(ATTACKER)).await.status(), + 404, + "a runner for another tenant must not read this blob" + ); + + h.cleanup_tenant(VICTIM).await; + h.cleanup_tenant(ATTACKER).await; + let _ = std::fs::remove_dir_all(&dir); +} + #[tokio::test] async fn empty_queue_leases_nothing() { let Some(h) = start().await else { return }; diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index 46992bd..bdd1dbb 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -27,7 +27,6 @@ pub struct AgentConfig { /// Base directory for content-addressed artifact blobs and per-run working /// dirs (`/blobs//`, `/work///`). pub artifact_store_base_path: String, - pub ssh_key_path: String, pub keycloak_url: Option, pub keycloak_realm: Option, pub keycloak_admin_username: Option, @@ -234,7 +233,6 @@ impl Default for AgentConfig { cve_monitor_schedule: "0 0 * * * *".to_string(), git_clone_base_path: "/tmp/compliance-scanner/repos".to_string(), artifact_store_base_path: "/data/compliance-scanner/artifacts".to_string(), - ssh_key_path: "/data/compliance-scanner/ssh/id_ed25519".to_string(), keycloak_url: None, keycloak_realm: None, keycloak_admin_username: None, diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 7d255cb..a9a91fe 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -116,6 +116,11 @@ pub struct ArtifactAuth { /// The secret credential: PAT, password, or bearer token. Encrypted at rest. pub secret: Option, /// Path to an SSH private key for git-over-SSH. + /// + /// **Ignored.** Git access is HTTPS-token only: the agent holds no git SSH + /// key, and an `ssh://`/`git@` URL is rejected rather than authenticated + /// with one. Kept so documents written before that still deserialize; + /// per-tenant key management is a later release. pub ssh_key_path: Option, /// Login URL for form-based authentication. pub login_url: Option, diff --git a/compliance-core/src/net_guard.rs b/compliance-core/src/net_guard.rs index 1c8749e..0ab8674 100644 --- a/compliance-core/src/net_guard.rs +++ b/compliance-core/src/net_guard.rs @@ -59,8 +59,10 @@ pub enum NetGuardError { const HTTP_SCHEMES: &[&str] = &["http", "https"]; /// Schemes accepted for a git remote. `file://` and `git://` are refused: the /// first reads the agent's own disk (including other tenants' checkouts), the -/// second is unauthenticated and cleartext. -const GIT_SCHEMES: &[&str] = &["http", "https", "ssh"]; +/// second is unauthenticated and cleartext. `ssh://` is refused too, because +/// the agent holds no git SSH key — see `pipeline::git::reject_ssh_url`, which +/// gives the same answer for the scp-style form that carries no scheme. +const GIT_SCHEMES: &[&str] = &["http", "https"]; /// Host suffixes that only mean something inside a private network. const INTERNAL_SUFFIXES: &[&str] = &[ @@ -451,7 +453,7 @@ mod tests { } #[test] - fn git_urls_refuse_file_and_git_schemes_but_allow_ssh() { + fn git_urls_refuse_file_git_and_ssh_schemes() { assert!(guard() .check_git_url("file:///tmp/compliance-scanner/repos/other-tenant/app") .is_err()); @@ -462,9 +464,11 @@ mod tests { assert!(guard() .check_git_url("https://example.com/org/repo.git") .is_ok()); + // The agent has no SSH key to offer, so an SSH remote could only + // authenticate as somebody else. assert!(guard() .check_git_url("ssh://git@example.com:22222/org/repo.git") - .is_ok()); + .is_err()); // …but not to an internal host. assert!(guard().check_git_url("https://gitea/org/repo.git").is_err()); } diff --git a/compliance-dashboard/src/components/pentest_wizard.rs b/compliance-dashboard/src/components/pentest_wizard.rs index 961ccc6..bbd5902 100644 --- a/compliance-dashboard/src/components/pentest_wizard.rs +++ b/compliance-dashboard/src/components/pentest_wizard.rs @@ -6,7 +6,6 @@ use crate::app::Route; use crate::infrastructure::dast::fetch_dast_targets; use crate::infrastructure::onboarding::fetch_targets; use crate::infrastructure::pentest::{create_pentest_session_wizard, lookup_repo_by_url}; -use crate::infrastructure::repositories::fetch_ssh_public_key; const DISCLAIMER_TEXT: &str = "I confirm that I have authorization to perform security testing \ against the specified target. I understand that penetration testing may cause disruption to the \ @@ -42,10 +41,6 @@ pub fn PentestWizard(show: Signal) -> Element { let existing_targets = use_resource(|| async { fetch_dast_targets().await.ok() }); let existing_repos = use_resource(|| async { fetch_targets().await.ok() }); - // SSH key state for private repos - let mut ssh_public_key = use_signal(String::new); - let mut ssh_key_loaded = use_signal(|| false); - // Step 2: Authentication let mut requires_auth = use_signal(|| false); let mut auth_mode = use_signal(|| "manual".to_string()); // "manual" | "auto_register" @@ -364,21 +359,6 @@ pub fn PentestWizard(show: Signal) -> Element { git_repo_url.set(e.value()); repo_looked_up.set(false); show_repo_dropdown.set(true); - // Fetch SSH key if it looks like an SSH URL - if is_ssh_url(&e.value()) && !*ssh_key_loaded.read() { - spawn(async move { - match fetch_ssh_public_key().await { - Ok(key) => { - ssh_public_key.set(key); - ssh_key_loaded.set(true); - } - Err(_) => { - ssh_public_key.set("(not available)".to_string()); - ssh_key_loaded.set(true); - } - } - }); - } }, onfocus: move |_| show_repo_dropdown.set(true), } @@ -390,7 +370,6 @@ pub fn PentestWizard(show: Signal) -> Element { let url_clone = url.clone(); let display_name = name.clone(); let display_url = url.clone(); - let is_ssh = is_ssh_url(&url_clone); rsx! { div { class: "wizard-dropdown-item", @@ -398,21 +377,6 @@ pub fn PentestWizard(show: Signal) -> Element { git_repo_url.set(url_clone.clone()); show_repo_dropdown.set(false); repo_looked_up.set(false); - // Auto-fetch SSH key if SSH URL selected - if is_ssh && !*ssh_key_loaded.read() { - spawn(async move { - match fetch_ssh_public_key().await { - Ok(key) => { - ssh_public_key.set(key); - ssh_key_loaded.set(true); - } - Err(_) => { - ssh_public_key.set("(not available)".to_string()); - ssh_key_loaded.set(true); - } - } - }); - } }, div { style: "font-weight: 500;", "{display_name}" } div { style: "font-size: 0.75rem; color: var(--text-secondary); font-family: monospace;", "{display_url}" } @@ -454,22 +418,18 @@ pub fn PentestWizard(show: Signal) -> Element { } } - // SSH deploy key section (shown for SSH URLs) + // SSH URLs are not supported: the agent holds no git + // SSH key, so say so before the scan fails. if show_ssh_section { div { class: "wizard-ssh-key", div { style: "display: flex; align-items: center; gap: 6px; margin-bottom: 6px;", Icon { icon: BsKeyFill, width: 14, height: 14 } - span { style: "font-size: 0.8rem; font-weight: 600;", "SSH Deploy Key" } + span { style: "font-size: 0.8rem; font-weight: 600;", "Use an HTTPS URL" } } - p { style: "font-size: 0.75rem; color: var(--text-secondary); margin: 0 0 6px 0;", - "Add this read-only deploy key to your repository settings:" - } - div { class: "wizard-ssh-key-box", - if ssh_public_key.read().is_empty() { - "Loading..." - } else { - "{ssh_public_key}" - } + p { style: "font-size: 0.75rem; color: var(--text-secondary); margin: 0;", + "SSH clone URLs are not supported. Use the HTTPS URL \ + (https://host/org/repo.git) and, for a private repository, \ + a personal access token or deploy token in the credentials below." } } } diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index e35c807..2635225 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -14,7 +14,6 @@ pub mod onboarding; pub mod pentest; pub mod platform; #[allow(clippy::too_many_arguments)] -pub mod repositories; pub mod sbom; pub mod scans; pub mod stats; diff --git a/compliance-dashboard/src/infrastructure/repositories.rs b/compliance-dashboard/src/infrastructure/repositories.rs deleted file mode 100644 index 309a906..0000000 --- a/compliance-dashboard/src/infrastructure/repositories.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! The agent's SSH deploy public key — shown so a read-only deploy key can be -//! added to private git targets. (The legacy repositories CRUD moved to the -//! unified onboarding/targets API.) - -use dioxus::prelude::*; - -/// Fetch the agent's SSH deploy public key. -#[server] -pub async fn fetch_ssh_public_key() -> Result { - let resp = super::agent_client::agent_get("/api/v1/settings/ssh-public-key") - .await? - .send() - .await - .map_err(|e| ServerFnError::new(e.to_string()))?; - - if !resp.status().is_success() { - return Err(ServerFnError::new("SSH key not available".to_string())); - } - - let body: serde_json::Value = resp - .json() - .await - .map_err(|e| ServerFnError::new(e.to_string()))?; - - Ok(body - .get("public_key") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string()) -} diff --git a/docs/features/pentest.md b/docs/features/pentest.md index 289672e..2055030 100644 --- a/docs/features/pentest.md +++ b/docs/features/pentest.md @@ -20,7 +20,7 @@ Click **New Pentest** on the dashboard to open the 4-step onboarding wizard: ### Step 1 — Target & Scope - **App URL** — enter manually or select from existing DAST targets (dropdown) -- **Git Repository URL** — enter manually or select from tracked repositories (dropdown). If an SSH URL is selected, the deploy key is displayed for easy copy +- **Git Repository URL** — enter manually or select from tracked repositories (dropdown). HTTPS URLs only; an SSH URL prompts you to use the HTTPS one with a read-only token instead - **Branch / Commit** — auto-populated when you click **Lookup** for a tracked repo - **App Type** and **Rate Limit** diff --git a/docs/guide/repositories.md b/docs/guide/repositories.md index 79cfc21..73c6fac 100644 --- a/docs/guide/repositories.md +++ b/docs/guide/repositories.md @@ -8,7 +8,7 @@ Repositories are the core resource in Prüfwerk. Each tracked repository is scan 2. Click **Add Repository** 3. Fill in the form: - **Name** -- a display name for the repository - - **Git URL** -- the clone URL (HTTPS or SSH), e.g. `https://github.com/org/repo.git` or `git@github.com:org/repo.git` + - **Git URL** -- the HTTPS clone URL, e.g. `https://github.com/org/repo.git` - **Default Branch** -- the branch to scan, e.g. `main` or `master` 4. Click **Add** @@ -20,21 +20,23 @@ The repository appears in the list immediately. It will not be scanned until you **Public repositories** can be cloned using an HTTPS URL with no additional setup. -**Private repositories** require SSH access. When you add a repository with an SSH URL (e.g. `git@github.com:org/repo.git`), Prüfwerk uses an SSH deploy key to authenticate. +**Private repositories** are cloned over HTTPS with a token you supply. Add the repository's HTTPS URL and, in the credentials section, a read-only access token for it. -### Getting the SSH Public Key +### Creating a Token -To grant Prüfwerk access to a private repository: +1. Create a read-only token in your Git hosting provider, scoped to the repository you are onboarding: + - **GitHub**: Settings > Developer settings > Personal access tokens (fine-grained), repository access limited to that repository, *Contents: Read-only* + - **GitLab**: Repository Settings > Repository > Deploy tokens, scope `read_repository` + - **Gitea**: Settings > Applications > Access tokens, scope `read:repository` +2. Add the repository in Prüfwerk with its **HTTPS** URL +3. Paste the token into the repository's credentials -1. Go to the **Repositories** page -2. The platform's SSH public key is available for copying -3. Add this key as a **deploy key** in your Git hosting provider: - - **GitHub**: Repository Settings > Deploy keys > Add deploy key - - **GitLab**: Repository Settings > Repository > Deploy keys - - **Gitea**: Repository Settings > Deploy Keys > Add Deploy Key +::: warning SSH URLs are not supported +`ssh://…` and `git@host:org/repo.git` URLs are rejected. Each tenant's token belongs to that tenant only; there is no shared platform deploy key, and adding one would mean every tenant's clones authenticating as the same identity. Per-tenant SSH keys are planned for a later release. +::: ::: tip -Deploy keys are scoped to a single repository and are read-only by default. This is the recommended approach for granting Prüfwerk access to private code. +Scope the token to a single repository and to read-only access. That is the smallest credential that lets Prüfwerk clone your code. ::: ## Configuring an Issue Tracker