Files
crank/crates/crank-registry/tests/integration/import_auth_binding.rs
T

571 lines
19 KiB
Rust

use super::common::*;
use std::{
fs,
os::unix::fs::PermissionsExt,
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
};
use crank_artifacts::{ArtifactRef, ArtifactStore};
use crank_core::{
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, BearerAuthConfig, ExecutionConfig,
Secret, SecretKind, SecretStatus, Workspace, WorkspaceId, WorkspaceStatus,
};
use crank_registry::{
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
CreateArtifactSourceRequest, CreateImportJobRequest, CreateSecretRequest,
CreateWorkspaceRequest, ImportAuthRequirement, ImportConflictMode, ImportJobId, ImportJobKind,
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, MASTER_KEY_CIPHER_CONTRACT,
MasterKeyIdentityCandidate, PostgresRegistry, RegistryError, RegistryOperation,
SaveAuthProfileRequest,
};
use serde_json::json;
use time::OffsetDateTime;
use tokio::time::{Duration as TokioDuration, sleep};
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
struct ImportSourceRoot(PathBuf);
impl ImportSourceRoot {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"crank-registry-import-auth-{}-{}",
std::process::id(),
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&path).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self(path)
}
}
impl Drop for ImportSourceRoot {
fn drop(&mut self) {
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
let _ = fs::remove_dir_all(&self.0);
}
}
fn timestamp() -> OffsetDateTime {
OffsetDateTime::now_utc()
}
async fn create_workspace(registry: &PostgresRegistry, id: &str) -> WorkspaceId {
let now = timestamp();
let workspace_id = WorkspaceId::new(id);
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: id.replace('_', "-"),
display_name: id.to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.unwrap();
workspace_id
}
async fn create_secret(registry: &PostgresRegistry, id: &str, workspace_id: &WorkspaceId) {
let now = timestamp();
registry
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
epoch: 1,
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
observed_at: &now,
})
.await
.unwrap();
let secret = Secret {
id: id.into(),
workspace_id: workspace_id.clone(),
name: format!("secret-{id}"),
kind: SecretKind::Token,
status: SecretStatus::Active,
current_version: 1,
created_at: now,
updated_at: now,
last_used_at: None,
};
registry
.create_secret(CreateSecretRequest {
secret: &secret,
ciphertext: "opaque-test-ciphertext",
key_version: "test-key-v1",
master_key_epoch: 1,
created_by: None,
})
.await
.unwrap();
}
fn profile(
id: &str,
workspace_id: &WorkspaceId,
kind: AuthKind,
config: AuthConfig,
) -> AuthProfile {
let now = timestamp();
AuthProfile {
id: id.into(),
workspace_id: workspace_id.clone(),
name: format!("profile-{id}"),
kind,
config,
created_at: now,
updated_at: now,
}
}
async fn save_profile(registry: &PostgresRegistry, profile: &AuthProfile) {
registry
.save_auth_profile(SaveAuthProfileRequest {
workspace_id: &profile.workspace_id,
profile,
})
.await
.unwrap();
}
async fn create_import_job(
registry: &PostgresRegistry,
root: &ImportSourceRoot,
job_number: usize,
) -> (ImportJobId, ArtifactSourceId, ArtifactRef) {
let store = ArtifactStore::open(&root.0).unwrap();
let artifact = store.put_registered(b"openapi: 3.1.0\n").unwrap();
let source_id = ArtifactSourceId::new(format!("src_import_auth_{job_number}"));
let now = timestamp();
let workspace_id = test_workspace_id();
registry
.create_artifact_source(CreateArtifactSourceRequest {
workspace_id: &workspace_id,
source_id: &source_id,
artifact: &artifact,
mime_type: "application/yaml",
sensitivity: ArtifactSourceSensitivity::Internal,
created_at: now,
})
.await
.unwrap();
let source = ImportJobSourceEnvelope {
source_id: source_id.clone(),
digest: artifact.artifact_ref().clone(),
};
let payload = json!({
"source": {
"source_id": source.source_id.as_str(),
"digest": source.digest.as_str(),
}
});
let id = ImportJobId::new(format!("job_import_auth_{job_number}"));
registry
.create_import_job(CreateImportJobRequest {
id: &id,
workspace_id: &workspace_id,
kind: ImportJobKind::OpenApi,
source_format: "openapi",
source_version: Some("v5"),
status: ImportJobStatus::Pending,
source: &source,
preview_payload: &payload,
created_at: &now,
expires_at: &(now + time::Duration::hours(1)),
})
.await
.unwrap();
(id, source_id, artifact.artifact_ref().clone())
}
fn operation(id: &str, profile_id: Option<&str>) -> RegistryOperation {
let mut operation = test_operation(id, 1, crank_core::OperationStatus::Draft);
operation.execution_config = ExecutionConfig {
auth_profile_ref: profile_id.map(Into::into),
..operation.execution_config
};
operation
}
async fn apply(
registry: &PostgresRegistry,
job_id: &ImportJobId,
drafts: &[ImportOperationDraft],
) -> Result<crank_registry::ImportJobApplyResult, RegistryError> {
let workspace_id = test_workspace_id();
let now = timestamp();
registry
.apply_import_job(ApplyImportJobRequest {
id: job_id,
workspace_id: &workspace_id,
application_key: "test-app-key",
conflict_mode: ImportConflictMode::Rename,
operations: drafts,
pre_skipped: &[],
finished_at: &now,
})
.await
}
async fn operation_count(database: &TestDatabase, ids: &[&str]) -> i64 {
let pool = database.raw_pool().await;
let count = sqlx::query_scalar::<_, i64>("select count(*) from operations where id = any($1)")
.bind(ids)
.fetch_one(&pool)
.await
.unwrap();
pool.close().await;
count
}
#[tokio::test]
async fn apply_accepts_current_compatible_profile_and_shared_secret_then_rejects_disabled_secret() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let workspace_id = test_workspace_id();
let secret_id = "secret_import_shared";
create_secret(&registry, secret_id, &workspace_id).await;
for profile_id in ["auth_import_a", "auth_import_b"] {
save_profile(
&registry,
&profile(
profile_id,
&workspace_id,
AuthKind::ApiKeyHeader,
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "x-api-key".to_owned(),
secret_id: secret_id.into(),
}),
),
)
.await;
}
let root = ImportSourceRoot::new();
let (job_id, _, _) = create_import_job(&registry, &root, 1).await;
let drafts = [
ImportOperationDraft {
operation_key: "first".to_owned(),
operation: operation("op_import_auth_first", Some("auth_import_a")),
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
parameter_name: "X-Api-Key".to_owned(),
}),
},
ImportOperationDraft {
operation_key: "second".to_owned(),
operation: operation("op_import_auth_second", Some("auth_import_b")),
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
parameter_name: "X-Api-Key".to_owned(),
}),
},
];
let result = apply(&registry, &job_id, &drafts).await.unwrap();
assert_eq!(result.created.len(), 2);
assert_eq!(
operation_count(
&database,
&["op_import_auth_first", "op_import_auth_second"]
)
.await,
2
);
let pool = database.raw_pool().await;
sqlx::query("update secrets set status = 'disabled' where id = $1")
.bind(secret_id)
.execute(&pool)
.await
.unwrap();
pool.close().await;
let (job_id, _, _) = create_import_job(&registry, &root, 2).await;
let disabled_error = apply(&registry, &job_id, &drafts).await.unwrap_err();
assert_eq!(
disabled_error.to_string(),
"import auth profile binding is unavailable"
);
assert_eq!(
operation_count(
&database,
&["op_import_auth_first", "op_import_auth_second"]
)
.await,
2
);
database.cleanup().await;
}
#[tokio::test]
async fn missing_and_foreign_profiles_have_the_same_safe_error_and_insert_no_operation() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let foreign_workspace = create_workspace(&registry, "ws_import_auth_foreign").await;
create_secret(&registry, "secret_import_foreign", &foreign_workspace).await;
save_profile(
&registry,
&profile(
"auth_import_foreign",
&foreign_workspace,
AuthKind::Bearer,
AuthConfig::Bearer(BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: "secret_import_foreign".into(),
}),
),
)
.await;
let root = ImportSourceRoot::new();
let (missing_job, _, _) = create_import_job(&registry, &root, 3).await;
let missing = [ImportOperationDraft {
operation_key: "missing".to_owned(),
operation: operation("op_import_auth_missing", Some("auth_import_absent")),
auth_requirement: Some(ImportAuthRequirement::Bearer),
}];
let missing_error = apply(&registry, &missing_job, &missing).await.unwrap_err();
let (foreign_job, _, _) = create_import_job(&registry, &root, 4).await;
let foreign = [ImportOperationDraft {
operation_key: "foreign".to_owned(),
operation: operation("op_import_auth_foreign_ref", Some("auth_import_foreign")),
auth_requirement: Some(ImportAuthRequirement::Bearer),
}];
let foreign_error = apply(&registry, &foreign_job, &foreign).await.unwrap_err();
assert_eq!(
missing_error.to_string(),
"import auth profile binding is unavailable"
);
assert_eq!(missing_error.to_string(), foreign_error.to_string());
assert_eq!(
operation_count(
&database,
&["op_import_auth_missing", "op_import_auth_foreign_ref"]
)
.await,
0
);
database.cleanup().await;
}
#[tokio::test]
async fn apply_rejects_kind_parameter_and_missing_current_version_before_mutation() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let workspace_id = test_workspace_id();
create_secret(&registry, "secret_import_mismatch", &workspace_id).await;
save_profile(
&registry,
&profile(
"auth_import_mismatch",
&workspace_id,
AuthKind::ApiKeyHeader,
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: "secret_import_mismatch".into(),
}),
),
)
.await;
let root = ImportSourceRoot::new();
let bad_requirements = [
ImportAuthRequirement::Bearer,
ImportAuthRequirement::ApiKeyHeader {
parameter_name: "X-Different".to_owned(),
},
];
for (index, requirement) in bad_requirements.into_iter().enumerate() {
let (job_id, _, _) = create_import_job(&registry, &root, 5 + index).await;
let operation_id = format!("op_import_auth_mismatch_{index}");
let draft = [ImportOperationDraft {
operation_key: operation_id.clone(),
operation: operation(&operation_id, Some("auth_import_mismatch")),
auth_requirement: Some(requirement),
}];
let error = apply(&registry, &job_id, &draft).await.unwrap_err();
assert_eq!(
error.to_string(),
"import auth profile binding is unavailable"
);
assert_eq!(operation_count(&database, &[&operation_id]).await, 0);
}
let pool = database.raw_pool().await;
sqlx::query("update secrets set current_version = 2 where id = $1")
.bind("secret_import_mismatch")
.execute(&pool)
.await
.unwrap();
pool.close().await;
let (job_id, _, _) = create_import_job(&registry, &root, 7).await;
let draft = [ImportOperationDraft {
operation_key: "missing-current".to_owned(),
operation: operation(
"op_import_auth_missing_current",
Some("auth_import_mismatch"),
),
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
parameter_name: "X-Api-Key".to_owned(),
}),
}];
let error = apply(&registry, &job_id, &draft).await.unwrap_err();
assert_eq!(
error.to_string(),
"import auth profile binding is unavailable"
);
assert_eq!(
operation_count(&database, &["op_import_auth_missing_current"]).await,
0
);
database.cleanup().await;
}
#[tokio::test]
async fn no_auth_requires_no_profile_reference() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let root = ImportSourceRoot::new();
let (job_id, _, _) = create_import_job(&registry, &root, 8).await;
let draft = [ImportOperationDraft {
operation_key: "inconsistent".to_owned(),
operation: operation("op_import_auth_no_requirement", Some("auth_nonexistent")),
auth_requirement: None,
}];
let error = apply(&registry, &job_id, &draft).await.unwrap_err();
assert_eq!(
error.to_string(),
"import auth profile binding is unavailable"
);
assert_eq!(
operation_count(&database, &["op_import_auth_no_requirement"]).await,
0
);
database.cleanup().await;
}
#[tokio::test]
async fn apply_waiting_on_secret_disable_rejects_without_partial_draft_mutation() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let workspace_id = test_workspace_id();
create_secret(&registry, "secret_import_race", &workspace_id).await;
save_profile(
&registry,
&profile(
"auth_import_race",
&workspace_id,
AuthKind::ApiKeyHeader,
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: "secret_import_race".into(),
}),
),
)
.await;
let root = ImportSourceRoot::new();
let (job_id, _, _) = create_import_job(&registry, &root, 9).await;
let drafts = vec![
ImportOperationDraft {
operation_key: "race-first".to_owned(),
operation: operation("op_import_auth_race_first", Some("auth_import_race")),
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
parameter_name: "X-Api-Key".to_owned(),
}),
},
ImportOperationDraft {
operation_key: "race-second".to_owned(),
operation: operation("op_import_auth_race_second", Some("auth_import_race")),
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
parameter_name: "X-Api-Key".to_owned(),
}),
},
];
let pool = database.raw_pool().await;
let mut disable_tx = pool.begin().await.unwrap();
sqlx::query("select id from secrets where workspace_id = $1 and id = $2 for update")
.bind(workspace_id.as_str())
.bind("secret_import_race")
.fetch_one(&mut *disable_tx)
.await
.unwrap();
let concurrent_registry = registry.clone();
let concurrent_job_id = job_id.clone();
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let apply_task = tokio::spawn(async move {
let _ = started_tx.send(());
let workspace_id = test_workspace_id();
let finished_at = timestamp();
concurrent_registry
.apply_import_job(ApplyImportJobRequest {
id: &concurrent_job_id,
workspace_id: &workspace_id,
application_key: "race-app-key",
conflict_mode: ImportConflictMode::Rename,
operations: &drafts,
pre_skipped: &[],
finished_at: &finished_at,
})
.await
});
started_rx.await.unwrap();
// Use a separate pool because the transaction holding the lock occupies
// the raw pool's only connection.
let observer_pool = database.raw_pool().await;
let mut waiting_for_secret_lock = false;
for _ in 0..100 {
waiting_for_secret_lock = sqlx::query_scalar::<_, bool>(
"select exists (
select 1 from pg_stat_activity
where wait_event_type = 'Lock'
and query like 'select s.status,%'
and query like '%for update of s%'
)",
)
.fetch_one(&observer_pool)
.await
.unwrap();
if waiting_for_secret_lock {
break;
}
sleep(TokioDuration::from_millis(10)).await;
}
assert!(
waiting_for_secret_lock,
"Apply should be waiting on the locked Secret row"
);
observer_pool.close().await;
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
.bind(workspace_id.as_str())
.bind("secret_import_race")
.execute(&mut *disable_tx)
.await
.unwrap();
disable_tx.commit().await.unwrap();
let result = apply_task.await.unwrap();
assert_eq!(
result.unwrap_err().to_string(),
"import auth profile binding is unavailable"
);
assert_eq!(
operation_count(
&database,
&["op_import_auth_race_first", "op_import_auth_race_second"]
)
.await,
0
);
pool.close().await;
database.cleanup().await;
}