feat(registry): add workspace-scoped artifact metadata

This commit is contained in:
bsodfather committed 2026-08-27 02:18:09 +03:00
1 parent 497e1b740f
commit 2eb185b14a
29 files changed
+2264 -181

No files matched your search

@@ -0,0 +1,507 @@
use crank_artifacts::{ArtifactError, ArtifactRef, ArtifactStore, MAX_ARTIFACT_BYTES};
use crank_core::WorkspaceId;
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
use crate::{
ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactDigest, ArtifactSourceCursor,
ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord,
ArtifactSourceSensitivity, CreateArtifactSourceRequest, DetachArtifactSourceRequest,
ListArtifactSourcesQuery, MAX_ARTIFACT_SOURCE_PAGE_SIZE, RegistryError, VerifiedArtifactSource,
};
use super::PostgresRegistry;
const SOURCE_ID_PREFIX: &str = "src_";
const MAX_SOURCE_ID_SUFFIX_BYTES: usize = 128;
const MAX_MIME_TYPE_BYTES: usize = 255;
impl PostgresRegistry {
pub async fn create_artifact_source(
&self,
request: CreateArtifactSourceRequest<'_>,
) -> Result<ArtifactSourceRecord, RegistryError> {
validate_create_request(&request)?;
let mut transaction = self.pool().begin().await?;
require_workspace(&mut transaction, request.workspace_id).await?;
ensure_blob(&mut transaction, &request).await?;
sqlx::query(
"insert into artifact_sources (
workspace_id, source_id, blob_digest, mime_type, sensitivity,
lifecycle, created_at, updated_at, detached_at
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)
on conflict (workspace_id, source_id) do nothing",
)
.bind(request.workspace_id.as_str())
.bind(request.source_id.as_str())
.bind(request.artifact.artifact_ref().digest_hex())
.bind(request.mime_type)
.bind(request.sensitivity.as_str())
.bind(request.created_at)
.execute(&mut *transaction)
.await?;
let recorded =
get_source_in_transaction(&mut transaction, request.workspace_id, request.source_id)
.await?
.ok_or_else(|| source_not_found(request.source_id))?;
if !is_create_replay(&recorded, &request) {
return Err(source_conflict(request.source_id));
}
transaction.commit().await?;
Ok(recorded)
}
pub async fn get_artifact_source(
&self,
workspace_id: &WorkspaceId,
source_id: &ArtifactSourceId,
) -> Result<ArtifactSourceRecord, RegistryError> {
validate_source_id(source_id)?;
let row = sqlx::query(SOURCE_SELECT)
.bind(workspace_id.as_str())
.bind(source_id.as_str())
.fetch_optional(self.pool())
.await?;
row.map(map_artifact_source)
.transpose()?
.ok_or_else(|| source_not_found(source_id))
}
pub async fn list_artifact_sources(
&self,
query: ListArtifactSourcesQuery<'_>,
) -> Result<ArtifactSourcePage, RegistryError> {
if query.cursor.is_some_and(|cursor| {
cursor.workspace_id != *query.workspace_id
|| !valid_source_id(cursor.source_id.as_str())
}) {
return Err(RegistryError::InvalidArtifactSource { field: "cursor" });
}
let limit = query.limit.min(MAX_ARTIFACT_SOURCE_PAGE_SIZE);
if limit == 0 {
return Ok(ArtifactSourcePage {
items: Vec::new(),
next_cursor: None,
});
}
let cursor_created_at = query.cursor.map(|cursor| cursor.created_at);
let cursor_source_id = query.cursor.map(|cursor| cursor.source_id.as_str());
let fetch_limit = i64::from(limit) + 1;
let rows = sqlx::query(
"select
s.workspace_id, s.source_id, s.blob_digest, s.mime_type,
s.sensitivity, s.lifecycle as source_lifecycle,
s.created_at as source_created_at, s.updated_at as source_updated_at,
s.detached_at,
b.artifact_ref, b.size_bytes,
b.storage_lifecycle as blob_lifecycle
from artifact_sources s
join artifact_blobs b on b.digest = s.blob_digest
where s.workspace_id = $1
and (
$2::timestamptz is null
or (s.created_at, s.source_id) > ($2::timestamptz, $3::text)
)
order by s.created_at asc, s.source_id asc
limit $4",
)
.bind(query.workspace_id.as_str())
.bind(cursor_created_at)
.bind(cursor_source_id)
.bind(fetch_limit)
.fetch_all(self.pool())
.await?;
let mut items = rows
.into_iter()
.map(map_artifact_source)
.collect::<Result<Vec<_>, _>>()?;
let has_more = items.len() > limit as usize;
if has_more {
items.pop();
}
let next_cursor = has_more.then(|| {
let last = items
.last()
.expect("a non-zero bounded page with an extra row retains one item");
ArtifactSourceCursor {
workspace_id: query.workspace_id.clone(),
created_at: last.created_at,
source_id: last.source_id.clone(),
}
});
Ok(ArtifactSourcePage { items, next_cursor })
}
pub async fn detach_artifact_source(
&self,
request: DetachArtifactSourceRequest<'_>,
) -> Result<ArtifactSourceRecord, RegistryError> {
validate_source_id(request.source_id)?;
let mut transaction = self.pool().begin().await?;
let mut recorded =
get_source_in_transaction(&mut transaction, request.workspace_id, request.source_id)
.await?
.ok_or_else(|| source_not_found(request.source_id))?;
if recorded.lifecycle == ArtifactSourceLifecycle::Detached {
if recorded.detached_at == Some(request.detached_at)
&& request.expected_updated_at == Some(recorded.created_at)
{
transaction.commit().await?;
return Ok(recorded);
}
return Err(source_conflict(request.source_id));
}
if request.detached_at < recorded.created_at
|| request
.expected_updated_at
.is_some_and(|expected| expected != recorded.updated_at)
{
return Err(source_conflict(request.source_id));
}
let updated = sqlx::query(
"update artifact_sources
set lifecycle = 'detached', updated_at = $1, detached_at = $1
where workspace_id = $2 and source_id = $3
and lifecycle = 'active' and updated_at = $4",
)
.bind(request.detached_at)
.bind(request.workspace_id.as_str())
.bind(request.source_id.as_str())
.bind(recorded.updated_at)
.execute(&mut *transaction)
.await?
.rows_affected();
if updated != 1 {
return Err(source_conflict(request.source_id));
}
recorded.lifecycle = ArtifactSourceLifecycle::Detached;
recorded.updated_at = request.detached_at;
recorded.detached_at = Some(request.detached_at);
transaction.commit().await?;
Ok(recorded)
}
pub async fn read_artifact_source(
&self,
store: &ArtifactStore,
workspace_id: &WorkspaceId,
source_id: &ArtifactSourceId,
) -> Result<VerifiedArtifactSource, RegistryError> {
let source = self.get_artifact_source(workspace_id, source_id).await?;
if source.lifecycle != ArtifactSourceLifecycle::Active
|| source.blob.lifecycle != ArtifactBlobLifecycle::Available
{
return Err(RegistryError::SourceUnavailable);
}
let store = store.clone();
let artifact_ref = source.blob.artifact_ref.clone();
let bytes = tokio::task::spawn_blocking(move || store.read(&artifact_ref))
.await
.map_err(|_| RegistryError::SourceUnavailable)?
.map_err(map_artifact_read_error)?;
let actual_size = u64::try_from(bytes.len()).map_err(|_| RegistryError::SourceIntegrity)?;
if actual_size != source.blob.size_bytes {
return Err(RegistryError::SourceIntegrity);
}
Ok(VerifiedArtifactSource { source, bytes })
}
}
const SOURCE_SELECT: &str = "select
s.workspace_id, s.source_id, s.blob_digest, s.mime_type,
s.sensitivity, s.lifecycle as source_lifecycle,
s.created_at as source_created_at, s.updated_at as source_updated_at,
s.detached_at,
b.artifact_ref, b.size_bytes,
b.storage_lifecycle as blob_lifecycle
from artifact_sources s
join artifact_blobs b on b.digest = s.blob_digest
where s.workspace_id = $1 and s.source_id = $2";
async fn require_workspace(
transaction: &mut Transaction<'_, Postgres>,
workspace_id: &WorkspaceId,
) -> Result<(), RegistryError> {
let exists =
sqlx::query_scalar::<_, bool>("select exists(select 1 from workspaces where id = $1)")
.bind(workspace_id.as_str())
.fetch_one(&mut **transaction)
.await?;
if exists {
Ok(())
} else {
Err(RegistryError::WorkspaceNotFound {
workspace_id: workspace_id.as_str().to_owned(),
})
}
}
async fn ensure_blob(
transaction: &mut Transaction<'_, Postgres>,
request: &CreateArtifactSourceRequest<'_>,
) -> Result<(), RegistryError> {
let digest = request.artifact.artifact_ref().digest_hex();
let size_bytes = i64::try_from(request.artifact.size_bytes()).map_err(|_| {
RegistryError::InvalidArtifactSource {
field: "size_bytes",
}
})?;
sqlx::query(
"insert into artifact_blobs (
digest, artifact_ref, size_bytes, storage_lifecycle,
claim_token, claim_expires_at, created_at, updated_at
) values ($1, $2, $3, 'available', null, null, $4, $4)
on conflict (digest) do nothing",
)
.bind(digest)
.bind(request.artifact.artifact_ref().as_str())
.bind(size_bytes)
.bind(request.created_at)
.execute(&mut **transaction)
.await?;
let row = sqlx::query(
"select artifact_ref, size_bytes from artifact_blobs where digest = $1 for update",
)
.bind(digest)
.fetch_one(&mut **transaction)
.await?;
let recorded_ref = row.try_get::<String, _>("artifact_ref")?;
let recorded_size = row.try_get::<i64, _>("size_bytes")?;
if recorded_ref != request.artifact.artifact_ref().as_str() || recorded_size != size_bytes {
return Err(source_conflict(request.source_id));
}
Ok(())
}
async fn get_source_in_transaction(
transaction: &mut Transaction<'_, Postgres>,
workspace_id: &WorkspaceId,
source_id: &ArtifactSourceId,
) -> Result<Option<ArtifactSourceRecord>, RegistryError> {
let row = sqlx::query(
"select
s.workspace_id, s.source_id, s.blob_digest, s.mime_type,
s.sensitivity, s.lifecycle as source_lifecycle,
s.created_at as source_created_at, s.updated_at as source_updated_at,
s.detached_at,
b.artifact_ref, b.size_bytes,
b.storage_lifecycle as blob_lifecycle
from artifact_sources s
join artifact_blobs b on b.digest = s.blob_digest
where s.workspace_id = $1 and s.source_id = $2
for update of s",
)
.bind(workspace_id.as_str())
.bind(source_id.as_str())
.fetch_optional(&mut **transaction)
.await?;
row.map(map_artifact_source).transpose()
}
fn map_artifact_source(row: PgRow) -> Result<ArtifactSourceRecord, RegistryError> {
let digest = row.try_get::<String, _>("blob_digest")?;
let artifact_ref_text = row.try_get::<String, _>("artifact_ref")?;
let artifact_ref = ArtifactRef::parse(&artifact_ref_text).map_err(|_| {
RegistryError::InvalidArtifactSource {
field: "artifact_ref",
}
})?;
if digest != artifact_ref.digest_hex() {
return Err(RegistryError::InvalidArtifactSource {
field: "blob_digest",
});
}
let size_bytes = row.try_get::<i64, _>("size_bytes")?;
let size_bytes =
u64::try_from(size_bytes).map_err(|_| RegistryError::InvalidArtifactSource {
field: "size_bytes",
})?;
let blob_lifecycle = match row.try_get::<String, _>("blob_lifecycle")?.as_str() {
"available" => ArtifactBlobLifecycle::Available,
"unavailable" => ArtifactBlobLifecycle::Unavailable,
_ => {
return Err(RegistryError::InvalidArtifactSource {
field: "storage_lifecycle",
});
}
};
let sensitivity = match row.try_get::<String, _>("sensitivity")?.as_str() {
"public" => ArtifactSourceSensitivity::Public,
"internal" => ArtifactSourceSensitivity::Internal,
"secret" => ArtifactSourceSensitivity::Secret,
_ => {
return Err(RegistryError::InvalidArtifactSource {
field: "sensitivity",
});
}
};
let lifecycle = match row.try_get::<String, _>("source_lifecycle")?.as_str() {
"active" => ArtifactSourceLifecycle::Active,
"detached" => ArtifactSourceLifecycle::Detached,
_ => {
return Err(RegistryError::InvalidArtifactSource { field: "lifecycle" });
}
};
let detached_at = row.try_get::<Option<time::OffsetDateTime>, _>("detached_at")?;
if (lifecycle == ArtifactSourceLifecycle::Active) != detached_at.is_none() {
return Err(RegistryError::InvalidArtifactSource {
field: "detached_at",
});
}
Ok(ArtifactSourceRecord {
workspace_id: WorkspaceId::new(row.try_get::<String, _>("workspace_id")?),
source_id: ArtifactSourceId::new(row.try_get::<String, _>("source_id")?),
blob: ArtifactBlobRecord {
digest: ArtifactDigest::new(digest),
artifact_ref,
size_bytes,
lifecycle: blob_lifecycle,
},
mime_type: row.try_get("mime_type")?,
sensitivity,
lifecycle,
created_at: row.try_get("source_created_at")?,
updated_at: row.try_get("source_updated_at")?,
detached_at,
})
}
fn validate_create_request(request: &CreateArtifactSourceRequest<'_>) -> Result<(), RegistryError> {
if !valid_source_id(request.source_id.as_str()) {
return Err(RegistryError::InvalidArtifactSource { field: "source_id" });
}
if !valid_mime_type(request.mime_type) {
return Err(RegistryError::InvalidArtifactSource { field: "mime_type" });
}
if !valid_artifact_size(request.artifact.size_bytes()) {
return Err(RegistryError::InvalidArtifactSource {
field: "size_bytes",
});
}
Ok(())
}
fn valid_artifact_size(size_bytes: usize) -> bool {
(1..=MAX_ARTIFACT_BYTES).contains(&size_bytes)
}
fn validate_source_id(source_id: &ArtifactSourceId) -> Result<(), RegistryError> {
if valid_source_id(source_id.as_str()) {
Ok(())
} else {
Err(RegistryError::InvalidArtifactSource { field: "source_id" })
}
}
fn valid_mime_type(value: &str) -> bool {
if value.len() > MAX_MIME_TYPE_BYTES {
return false;
}
let Some((type_name, subtype)) = value.split_once('/') else {
return false;
};
!type_name.is_empty()
&& !subtype.is_empty()
&& !subtype.contains('/')
&& type_name.bytes().all(is_mime_token_byte)
&& subtype.bytes().all(is_mime_token_byte)
}
fn is_mime_token_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
)
}
fn valid_source_id(value: &str) -> bool {
let Some(suffix) = value.strip_prefix(SOURCE_ID_PREFIX) else {
return false;
};
!suffix.is_empty()
&& suffix.len() <= MAX_SOURCE_ID_SUFFIX_BYTES
&& suffix
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
}
fn is_create_replay(
recorded: &ArtifactSourceRecord,
request: &CreateArtifactSourceRequest<'_>,
) -> bool {
recorded.lifecycle == ArtifactSourceLifecycle::Active
&& recorded.blob.digest.as_str() == request.artifact.artifact_ref().digest_hex()
&& recorded.blob.artifact_ref == *request.artifact.artifact_ref()
&& recorded.blob.size_bytes == request.artifact.size_bytes() as u64
&& recorded.mime_type == request.mime_type
&& recorded.sensitivity == request.sensitivity
}
fn map_artifact_read_error(error: ArtifactError) -> RegistryError {
match error {
ArtifactError::NotFound | ArtifactError::UnsafeRoot | ArtifactError::Storage => {
RegistryError::SourceUnavailable
}
ArtifactError::Integrity
| ArtifactError::InvalidReference
| ArtifactError::EmptySource
| ArtifactError::SourceTooLarge => RegistryError::SourceIntegrity,
}
}
fn source_not_found(source_id: &ArtifactSourceId) -> RegistryError {
RegistryError::SourceNotFound {
source_id: source_id.as_str().to_owned(),
}
}
fn source_conflict(source_id: &ArtifactSourceId) -> RegistryError {
RegistryError::SourceConflict {
source_id: source_id.as_str().to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validates_bounded_source_identity_and_metadata() {
assert!(valid_source_id("src_openapi-1"));
assert!(valid_mime_type("application/yaml"));
assert!(valid_artifact_size(1));
assert!(valid_artifact_size(MAX_ARTIFACT_BYTES));
for invalid in ["source", "src_", "src_bad.value"] {
assert!(!valid_source_id(invalid));
}
for invalid in ["text/plain\n", "text", "text/plain/extra", "text/(plain)"] {
assert!(!valid_mime_type(invalid));
}
assert!(!valid_artifact_size(0));
assert!(!valid_artifact_size(MAX_ARTIFACT_BYTES + 1));
}
#[test]
fn artifact_failures_map_to_redacted_outcomes() {
assert!(matches!(
map_artifact_read_error(ArtifactError::NotFound),
RegistryError::SourceUnavailable
));
assert!(matches!(
map_artifact_read_error(ArtifactError::Integrity),
RegistryError::SourceIntegrity
));
}
}
@@ -2,6 +2,7 @@ mod agent;
mod agent_catalog;
mod api_key;
mod approval;
mod artifact_source;
mod auth;
mod connection;
mod import_job;