feat(import): bind OpenAPI security schemes safely
This commit is contained in:
1 parent
c562d5368d
commit
41a0e46110
38 files changed
+4651
-590
No files matched your search
@@ -136,6 +136,8 @@ pub enum RegistryError {
|
||||
ImportJobNotFound { job_id: String },
|
||||
#[error("import job {job_id} was already applied with different parameters")]
|
||||
ImportJobAlreadyApplied { job_id: String },
|
||||
#[error("import auth profile binding is unavailable")]
|
||||
ImportAuthBindingUnavailable,
|
||||
#[error("unsupported enum representation for field {field}")]
|
||||
InvalidEnumRepresentation { field: &'static str },
|
||||
#[error("invalid numeric value for field {field}: {value}")]
|
||||
|
||||
@@ -47,14 +47,15 @@ pub mod requests {
|
||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
DecideApprovalRequest, DetachArtifactSourceRequest, ExpireApprovalRequest,
|
||||
FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode, ImportJobSourceEnvelope,
|
||||
ImportOperationDraft, ListApprovalRequestsQuery, ListArtifactSourcesQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MasterKeyIdentityCandidate,
|
||||
PublishAgentRequest, PublishRequest, RecordOnboardingCompletionRequest,
|
||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RotateSecretRequest,
|
||||
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, SaveAuthProfileRequest,
|
||||
SaveDescriptorMetadataRequest, SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest,
|
||||
UpdateAgentSummaryRequest, UpdateWorkspaceRequest, UsageQuery,
|
||||
FinishApprovalRequest, FinishImportJobRequest, ImportAuthRequirement, ImportConflictMode,
|
||||
ImportJobSourceEnvelope, ImportOperationDraft, ListApprovalRequestsQuery,
|
||||
ListArtifactSourcesQuery, ListInvocationLogsQuery, ListProductEventsQuery,
|
||||
MasterKeyIdentityCandidate, PublishAgentRequest, PublishRequest,
|
||||
RecordOnboardingCompletionRequest, RecordOnboardingMilestoneRequest,
|
||||
RecoverAdminPasswordRequest, RotateSecretRequest, SaveAgentBindingsRequest,
|
||||
SaveAgentCatalogConfigRequest, SaveAuthProfileRequest, SaveDescriptorMetadataRequest,
|
||||
SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest, UpdateAgentSummaryRequest,
|
||||
UpdateWorkspaceRequest, UsageQuery,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -82,19 +83,20 @@ pub use model::{
|
||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
DecideApprovalRequest, DescriptorKind, DescriptorMetadata, DetachArtifactSourceRequest,
|
||||
ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode,
|
||||
ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, InvitationRecord,
|
||||
InvocationHistoryLoss, InvocationHistoryLossCategory, InvocationHistoryWriteOutcome,
|
||||
InvocationLogRecord, InvocationRetentionOutcome, InvocationRetentionPolicy,
|
||||
InvocationRetentionStatus, ListApprovalRequestsQuery, ListArtifactSourcesQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MASTER_KEY_CIPHER_CONTRACT,
|
||||
MAX_ARTIFACT_CLAIM_RECOVERY_BATCH, MAX_ARTIFACT_SOURCE_PAGE_SIZE, MasterKeyIdentityCandidate,
|
||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus, MembershipRecord,
|
||||
OnboardingMilestoneResult, OnboardingPresentationMilestone, OperationAgentRef,
|
||||
OperationSampleMetadata, OperationStateExpectation, OperationSummary, OperationUsageSummary,
|
||||
OperationVersionRecord, Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest,
|
||||
PublishRequest, PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
||||
ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest, ImportAuthRequirement,
|
||||
ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft,
|
||||
InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
InvocationHistoryWriteOutcome, InvocationLogRecord, InvocationRetentionOutcome,
|
||||
InvocationRetentionPolicy, InvocationRetentionStatus, ListApprovalRequestsQuery,
|
||||
ListArtifactSourcesQuery, ListInvocationLogsQuery, ListProductEventsQuery,
|
||||
MASTER_KEY_CIPHER_CONTRACT, MAX_ARTIFACT_CLAIM_RECOVERY_BATCH, MAX_ARTIFACT_SOURCE_PAGE_SIZE,
|
||||
MasterKeyIdentityCandidate, MasterKeyIdentityRecord, MasterKeyRotationRecord,
|
||||
MasterKeyRotationStatus, MembershipRecord, OnboardingMilestoneResult,
|
||||
OnboardingPresentationMilestone, OperationAgentRef, OperationSampleMetadata,
|
||||
OperationStateExpectation, OperationSummary, OperationUsageSummary, OperationVersionRecord,
|
||||
Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest, PublishRequest,
|
||||
PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RegistryOperation,
|
||||
RotateSecretRequest, SampleKind, SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest,
|
||||
SaveAuthProfileRequest, SaveDescriptorMetadataRequest, SaveSampleMetadataRequest,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
|
||||
ApprovalRequestId, ApprovalRequestStatus, AuthProfile, DescriptorId, ExecutionErrorCode,
|
||||
ExportMode, InvitationToken, InvocationLevel, InvocationLog, InvocationLogId, InvocationSource,
|
||||
InvocationStatus, MembershipRole, OnboardingProjection, Operation, OperationId,
|
||||
OperationSecurityLevel, OperationStatus, PlatformApiKey, PlatformApiKeyId, ProductEvent,
|
||||
ProductEventId, ProductEventKind, Protocol, SampleId, Secret, SecretId, SecretVersion,
|
||||
ToolSelectionPolicy, UsagePeriod, UsageRollup, User, UserId, UserSessionId, Workspace,
|
||||
WorkspaceId,
|
||||
ApprovalRequestId, ApprovalRequestStatus, AuthKind, AuthProfile, DescriptorId,
|
||||
ExecutionErrorCode, ExportMode, InvitationToken, InvocationLevel, InvocationLog,
|
||||
InvocationLogId, InvocationSource, InvocationStatus, MembershipRole, OnboardingProjection,
|
||||
Operation, OperationId, OperationSecurityLevel, OperationStatus, PlatformApiKey,
|
||||
PlatformApiKeyId, ProductEvent, ProductEventId, ProductEventKind, Protocol, SampleId, Secret,
|
||||
SecretId, SecretVersion, ToolSelectionPolicy, UsagePeriod, UsageRollup, User, UserId,
|
||||
UserSessionId, Workspace, WorkspaceId,
|
||||
};
|
||||
use crank_mapping::MappingSet;
|
||||
use crank_schema::Schema;
|
||||
@@ -648,6 +648,29 @@ pub enum ImportConflictMode {
|
||||
pub struct ImportOperationDraft {
|
||||
pub operation_key: String,
|
||||
pub operation: RegistryOperation,
|
||||
/// The effective single-scheme requirement selected for this operation.
|
||||
/// The registry checks it against the referenced profile inside Apply.
|
||||
pub auth_requirement: Option<ImportAuthRequirement>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum ImportAuthRequirement {
|
||||
Bearer,
|
||||
Basic,
|
||||
ApiKeyHeader { parameter_name: String },
|
||||
ApiKeyQuery { parameter_name: String },
|
||||
}
|
||||
|
||||
impl ImportAuthRequirement {
|
||||
pub const fn kind(&self) -> AuthKind {
|
||||
match self {
|
||||
Self::Bearer => AuthKind::Bearer,
|
||||
Self::Basic => AuthKind::Basic,
|
||||
Self::ApiKeyHeader { .. } => AuthKind::ApiKeyHeader,
|
||||
Self::ApiKeyQuery { .. } => AuthKind::ApiKeyQuery,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::*;
|
||||
use crate::{ArtifactSourceId, ImportJobSourceEnvelope};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{AuthConfig, AuthProfile, AuthProfileId, SecretId};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
||||
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
||||
@@ -388,6 +390,10 @@ async fn apply_import_job_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the complete binding set before the first Operation insert.
|
||||
// This transaction-level check closes the gap between preview and Apply.
|
||||
validate_import_auth_bindings(tx, request.workspace_id, request.operations).await?;
|
||||
|
||||
let mut result = ImportJobApplyResult {
|
||||
application_key: request.application_key.to_owned(),
|
||||
skipped: request.pre_skipped.to_vec(),
|
||||
@@ -485,6 +491,190 @@ async fn apply_import_job_transaction(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn validate_import_auth_bindings(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operations: &[crate::ImportOperationDraft],
|
||||
) -> Result<(), RegistryError> {
|
||||
let mut requirements_by_profile = BTreeMap::<String, Vec<&crate::ImportAuthRequirement>>::new();
|
||||
for draft in operations {
|
||||
match (
|
||||
draft.auth_requirement.as_ref(),
|
||||
draft.operation.execution_config.auth_profile_ref.as_ref(),
|
||||
) {
|
||||
(None, None) => {}
|
||||
(Some(requirement), Some(profile_id)) => requirements_by_profile
|
||||
.entry(profile_id.as_str().to_owned())
|
||||
.or_default()
|
||||
.push(requirement),
|
||||
_ => return Err(RegistryError::ImportAuthBindingUnavailable),
|
||||
}
|
||||
}
|
||||
if requirements_by_profile.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Read the current workspace's profile config first to discover Secret
|
||||
// references. Secret rows are locked in stable order before profile rows,
|
||||
// matching save_auth_profile's secret-then-profile write order.
|
||||
let mut observed_profiles = BTreeMap::<String, AuthProfile>::new();
|
||||
let mut secret_ids = BTreeMap::<String, SecretId>::new();
|
||||
for profile_id in requirements_by_profile.keys() {
|
||||
let profile = read_import_auth_profile(tx, workspace_id, profile_id, false)
|
||||
.await?
|
||||
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||
let requirements = &requirements_by_profile[profile_id];
|
||||
if !requirements
|
||||
.iter()
|
||||
.all(|requirement| auth_profile_matches(profile_id, &profile, requirement))
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
for secret_id in profile.config.secret_ids() {
|
||||
secret_ids
|
||||
.entry(secret_id.as_str().to_owned())
|
||||
.or_insert_with(|| secret_id.clone());
|
||||
}
|
||||
observed_profiles.insert(profile_id.clone(), profile);
|
||||
}
|
||||
|
||||
for secret_id in secret_ids.values() {
|
||||
let row = sqlx::query(
|
||||
"select s.status,
|
||||
exists (
|
||||
select 1 from secret_versions sv
|
||||
where sv.secret_id = s.id and sv.version = s.current_version
|
||||
) as has_current_version
|
||||
from secrets s
|
||||
where s.workspace_id = $1 and s.id = $2
|
||||
for update of s",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(secret_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
let Some(row) = row else {
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
};
|
||||
if row.try_get::<String, _>("status")? != "active"
|
||||
|| !row.try_get::<bool, _>("has_current_version")?
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
// The profile may have changed while its former Secret rows were being
|
||||
// locked. Lock profile rows only after Secrets (the order used by profile
|
||||
// updates), then compare the binding config and revalidate compatibility.
|
||||
for (profile_id, observed) in &observed_profiles {
|
||||
let current = read_import_auth_profile(tx, workspace_id, profile_id, true)
|
||||
.await?
|
||||
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||
if current.id != observed.id
|
||||
|| current.workspace_id != observed.workspace_id
|
||||
|| current.kind != observed.kind
|
||||
|| current.config != observed.config
|
||||
|| !requirements_by_profile[profile_id]
|
||||
.iter()
|
||||
.all(|requirement| auth_profile_matches(profile_id, ¤t, requirement))
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_import_auth_profile(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
profile_id: &str,
|
||||
lock: bool,
|
||||
) -> Result<Option<AuthProfile>, RegistryError> {
|
||||
let query = if lock {
|
||||
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2
|
||||
for update"
|
||||
} else {
|
||||
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2"
|
||||
};
|
||||
let row = sqlx::query(query)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
super::build_auth_profile(
|
||||
row.try_get("id")?,
|
||||
row.try_get("workspace_id")?,
|
||||
row.try_get("name")?,
|
||||
row.try_get("kind")?,
|
||||
row.try_get("config_json")?,
|
||||
row.try_get("created_at")?,
|
||||
row.try_get("updated_at")?,
|
||||
)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn auth_profile_matches(
|
||||
expected_profile_id: &str,
|
||||
profile: &AuthProfile,
|
||||
requirement: &crate::ImportAuthRequirement,
|
||||
) -> bool {
|
||||
if profile.id != AuthProfileId::new(expected_profile_id)
|
||||
|| profile.kind != profile.config.kind()
|
||||
|| profile.kind != requirement.kind()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match (requirement, &profile.config) {
|
||||
(crate::ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
|
||||
| (crate::ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
|
||||
(
|
||||
crate::ImportAuthRequirement::ApiKeyHeader { parameter_name },
|
||||
AuthConfig::ApiKeyHeader(config),
|
||||
) => {
|
||||
is_valid_auth_header_name(&config.header_name)
|
||||
&& is_valid_auth_header_name(parameter_name)
|
||||
&& config.header_name.eq_ignore_ascii_case(parameter_name)
|
||||
}
|
||||
(
|
||||
crate::ImportAuthRequirement::ApiKeyQuery { parameter_name },
|
||||
AuthConfig::ApiKeyQuery(config),
|
||||
) => config.param_name == *parameter_name,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_auth_header_name(value: &str) -> bool {
|
||||
value.len() <= 128
|
||||
&& !value.is_empty()
|
||||
&& value.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric()
|
||||
|| matches!(
|
||||
byte,
|
||||
b'!' | b'#'
|
||||
| b'$'
|
||||
| b'%'
|
||||
| b'&'
|
||||
| b'\''
|
||||
| b'*'
|
||||
| b'+'
|
||||
| b'-'
|
||||
| b'.'
|
||||
| b'^'
|
||||
| b'_'
|
||||
| b'`'
|
||||
| b'|'
|
||||
| b'~'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_source_envelope(
|
||||
source: &ImportJobSourceEnvelope,
|
||||
preview_payload: &Value,
|
||||
|
||||
@@ -5,6 +5,7 @@ mod integration {
|
||||
mod artifact_sources;
|
||||
mod common;
|
||||
mod credential_touch;
|
||||
mod import_auth_binding;
|
||||
mod master_key_identity;
|
||||
mod migrations;
|
||||
mod observability;
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
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(®istry, secret_id, &workspace_id).await;
|
||||
for profile_id in ["auth_import_a", "auth_import_b"] {
|
||||
save_profile(
|
||||
®istry,
|
||||
&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(®istry, &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(®istry, &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(®istry, &root, 2).await;
|
||||
let disabled_error = apply(®istry, &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(®istry, "ws_import_auth_foreign").await;
|
||||
create_secret(®istry, "secret_import_foreign", &foreign_workspace).await;
|
||||
save_profile(
|
||||
®istry,
|
||||
&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(®istry, &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(®istry, &missing_job, &missing).await.unwrap_err();
|
||||
|
||||
let (foreign_job, _, _) = create_import_job(®istry, &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(®istry, &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(®istry, "secret_import_mismatch", &workspace_id).await;
|
||||
save_profile(
|
||||
®istry,
|
||||
&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(®istry, &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(®istry, &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(®istry, &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(®istry, &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(®istry, &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(®istry, &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(®istry, "secret_import_race", &workspace_id).await;
|
||||
save_profile(
|
||||
®istry,
|
||||
&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(®istry, &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;
|
||||
}
|
||||
Reference in new issue
Block a user