8000 Relations: a reader or writer learns nothing of a version it may not see (0.1.4) by ynishi · Pull Request #26 · ynishi/evalhub · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*"]

[workspace.package]
version = "0.1.3"
version = "0.1.4"
edition = "2024"
# sqlx 0.9 declares rust-version 1.94.0; the workspace cannot claim less.
rust-version = "1.94"
Expand All @@ -21,10 +21,10 @@ categories = ["web-programming::http-server", "science"]

[workspace.dependencies]
# internal
evalhub-schema = { path = "crates/evalhub-schema", version = "0.1.3" }
evalhub-core = { path = "crates/evalhub-core", version = "0.1.3" }
evalhub-query = { path = "crates/evalhub-query", version = "0.1.3" }
evalhub-store = { path = "crates/evalhub-store", version = "0.1.3" }
evalhub-schema = { path = "crates/evalhub-schema", version = "0.1.4" }
evalhub-core = { path = "crates/evalhub-core", version = "0.1.4" }
evalhub-query = { path = "crates/evalhub-query", version = "0.1.4" }
evalhub-store = { path = "crates/evalhub-store", version = "0.1.4" }

# serde
serde = { version = "1", features = ["derive"] }
Expand Down
5 changes: 3 additions & 2 deletions compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ services:
retries: 12

minio:
image: quay.io/minio/minio
image: cgr.dev/chainguard/minio:latest@sha256:bd014394a80898e68c149f2311fdf8d5a2c2f3bb2c33b9327ae6d02b4b065ae1
command: server /data --console-address :9001
environment:
MINIO_ROOT_USER: evalhub
Expand All @@ -42,7 +42,8 @@ services:

# The hub does not create its bucket; this does, once, then exits.
minio-init:
image: quay.io/minio/mc
# The MinIO image ships `mc`; quay.io/minio/mc is no longer pullable.
image: cgr.dev/chainguard/minio:latest@sha256:bd014394a80898e68c149f2311fdf8d5a2c2f3bb2c33b9327ae6d02b4b065ae1
depends_on:
- minio
entrypoint: >
Expand Down
13 changes: 13 additions & 0 deletions crates/evalhub-schema/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@
//! that an Eval exists, its `version_id`, and the `content_hash` commitment —
//! enough to know the Card is anchored to something specific — and nothing
//! else. No title, no runs, no attachment URLs.
//!
//! The Card's own body does not reveal more than its edges. On every read
//! that returns a body, a `relations[]` element whose target the reader may
//! not see is removed and listed under `withheld.relations` as the same
//! commitment (`type`, `version_id`, `content_hash`). The body returned is
//! then not the stored one, and its `content_hash` does not match it. A
//! query's `relations.to` condition matches only targets the caller may
//! see, so a search cannot confirm a private name either.
//!
//! A write learns no more than a read. A target the writer may not see is
//! stored unresolved, exactly as one that does not exist: the response and
//! the `refs_resolved` badge are the same in both cases. The edge resolves
//! for a reader once the target becomes visible to them.

use chrono::{DateTime, Utc};
use schemars::JsonSchema;
Expand Down
13 changes: 12 additions & 1 deletion crates/evalhub-server/src/api/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use evalhub_store::records;
use evalhub_store::registry::{self, Kind};
use evalhub_store::{query_sql, relations};

use crate::api::relations::RelationDto;
use crate::api::relations::{RelationDto, Withheld, withhold};
use crate::auth::MaybeAuth;
use crate::error::ApiError;
use crate::state::AppState;
Expand Down Expand Up @@ -98,6 +98,11 @@ pub struct QueryHitDto {
/// Outgoing edges, with `expand=relations`.
#[serde(skip_serializing_if = "Option::is_none")]
pub relations: Option<Vec<RelationDto>>,
/// What was removed from `record` because the caller may not see it.
/// When present, `record` is not the stored body and does not match
/// `content_hash`.
#[serde(skip_serializing_if = "Option::is_none")]
pub withheld: Option<Withheld>,
}

impl From<query_sql::QueryHit> for QueryHitDto {
Expand All @@ -123,6 +128,7 @@ impl From<query_sql::QueryHit> for QueryHitDto {
record: hit.body,
fingerprints: None,
relations: None,
withheld: None,
}
}
}
Expand Down Expand Up @@ -207,10 +213,15 @@ async fn query(

let want_fingerprints = compiled.expand.contains(&ir::Expand::Fingerprints);
let want_relations = compiled.expand.contains(&ir::Expand::Relations);
let version_ids: Vec<_> = hits.iter().map(|h| h.version_id).collect();
let hidden = relations::hidden_targets(pool, &version_ids, &caller_ns).await?;
let mut items = Vec::with_capacity(hits.len());
for hit in hits {
let version_id = hit.version_id;
let mut dto = QueryHitDto::from(hit);
if let (Some(record), Some(h)) = (dto.record.as_mut(), hidden.get(&version_id)) {
dto.withheld = withhold(record, h);
}
if want_fingerprints {
let map = records::load_fingerprints(pool, version_id).await?;
dto.fingerprints = Some(
Expand Down
22 changes: 22 additions & 0 deletions crates/evalhub-server/src/api/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,17 @@
//! "record": { ...the canonical body... },
//! "fingerprints": { "model": "…", ... }, // expand=fingerprints
//! "relations": [...], // expand=relations
//! "withheld": { "relations": [...] }, // elements removed for this reader
//! "tombstone": { "at", "reason", "note" } // when tombstoned; record is absent
//! }
//! ```
//!
//! `withheld` is set when the reader may not see a version the record's
//! `relations[]` points at: the element is removed from `record` and
//! listed there as a commitment (`crate::api::relations` has the rule).
//! `record` then differs from the stored body and `content_hash` does not
//! match it.
//!
//! `POST` semantics — idempotent on `content_hash`, new `seq` otherwise —
//! are in `evalhub_store::records`. `?label=` on `POST` labels the new
//! version in the same transaction (`409 label_in_use` if taken).
Expand Down Expand Up @@ -284,6 +291,11 @@ pub struct VersionEnvelope {
/// The version's outgoing edges, with `expand=relations`.
#[serde(skip_serializing_if = "Option::is_none")]
pub relations: Option<Vec<crate::api::relations::RelationDto>>,
/// What was removed from `record` because the caller may not see it.
/// When present, `record` is not the stored body and does not match
/// `content_hash`.
#[serde(skip_serializing_if = "Option::is_none")]
pub withheld: Option<crate::api::relations::Withheld>,
/// Present when the version was withdrawn; `record` is then absent.
#[serde(skip_serializing_if = "Option::is_none")]
pub tombstone: Option<TombstoneDto>,
Expand Down Expand Up @@ -313,6 +325,7 @@ impl VersionEnvelope {
record,
fingerprints: None,
relations: None,
withheld: None,
tombstone: None,
}
}
Expand Down Expand Up @@ -582,6 +595,7 @@ async fn post(
.collect()
};

let readable_ns = caller.namespaces();
let outcome = records::create_or_append(
state.db()?,
NewVersion {
Expand All @@ -592,6 +606,7 @@ async fn post(
content_hash: hash.as_bytes(),
label: query.label.as_deref(),
actor: caller.actor(),
readable_ns: &readable_ns,
fingerprints: &fingerprint_rows,
results: &results,
relations: &relations,
Expand Down Expand Up @@ -657,6 +672,13 @@ async fn get(
.ok_or(ApiError::NotFound)?;
let version_id = stored.meta.version_id;
let mut env = VersionEnvelope::from_stored(stored);
if let Some(record) = env.record.as_mut() {
let hidden =
evalhub_store::relations::hidden_targets(pool, &[version_id], &caller_ns).await?;
env.withheld = hidden
.get(&version_id)
.and_then(|h| crate::api::relations::withhold(record, h));
}
let expand: Vec<&str> = query
.expand
.as_deref()
Expand Down
83 changes: 82 additions & 1 deletion crates/evalhub-server/src/api/relations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@
//! title. That is the commitment the design promises, and it is why a
//! public Card may cite a private Eval without leaking it.
//!
//! The same holds for the body of the version the edge leaves. Every read
//! that returns a record body (`GET …/{name}`, `POST …/query`) removes the
//! `relations[]` elements whose target the reader may not see and lists
//! them, as the same commitment, under `withheld.relations` in the
//! envelope ([`withhold`]). A body with elements withheld is no longer the
//! stored body, so its `content_hash` does not match it: a client that
//! verifies the hash does so on responses without `withheld`.
//!
//! A write never learns more than a read. A target the writer may not see
//! is stored unresolved, like one that does not exist, and the response
//! and the `refs_resolved` badge are the same in both cases. Reading such
//! an edge, a caller without access gets the text back as `unresolved`;
//! once the target is readable to them it resolves.
//!
//! An `external:` or `hf:` target, and a `{ns}/{name}@{seq}` that does not
//! exist yet, appear as text: `{ external: "…" }` and
//! `{ unresolved: "…" }`. A Card published before the Eval it cites is
Expand Down Expand Up @@ -57,7 +71,8 @@ use evalhub_schema::error::{ErrorCode, ErrorEntry};
use evalhub_store::auth::Scope;
use evalhub_store::records::{self, RecordType};
use evalhub_store::relations::{
self, Direction, EdgeEnd, RelationTarget, ResolvedTarget, StoredRelation, TraverseParams,
self, Direction, EdgeEnd, HiddenTarget, RelationTarget, ResolvedTarget, StoredRelation,
TraverseParams,
};

use crate::auth::{Auth, MaybeAuth};
Expand Down Expand Up @@ -164,6 +179,71 @@ impl From<ResolvedTarget> for TargetDto {
}
}

/// What a read removed from a record body because the reader may not see
/// it. Present in an envelope only when something was removed.
#[derive(Debug, Serialize, JsonSchema)]
pub struct Withheld {
/// One entry per removed `relations[]` element, in body order.
pub relations: Vec<WithheldRelation>,
}

/// A removed `relations[]` element, reduced to the commitment: the same
/// `version_id` and `content_hash` a `private` endpoint of
/// `GET …/relations` shows.
#[derive(Debug, Serialize, JsonSchema)]
pub struct WithheldRelation {
/// Registry id of the relation type of the element.
#[serde(rename = "type")]
pub relation_type: String,
/// The version it points at.
pub version_id: String,
/// sha256 of that version's canonical body.
pub content_hash: String,
}

/// Remove from `body.relations[]` every element whose `(type, to)` names
/// one of `hidden`, and say what was removed. `None` when nothing was.
///
/// `to` is parsed rather than compared as text, so a spelling the parser
/// accepts but the stored text does not match (`@01`) is still caught.
pub fn withhold(body: &mut Value, hidden: &[HiddenTarget]) -> Option<Withheld> {
if hidden.is_empty() {
return None;
}
let elements = body.get_mut("relations")?.as_array_mut()?;
let mut removed = Vec::new();
elements.retain(|element| {
let Some(relation_type) = element.get("type").and_then(Value::as_str) else {
return true;
};
let Some(ParsedTarget::Version { ns, name, seq }) = element
.get("to")
.and_then(Value::as_str)
.and_then(parse_relation_target)
else {
return true;
};
let found = hidden.iter().find(|h| {
h.relation_type == relation_type
&& h.ns == ns
&& h.name == name
&& i64::from(h.seq) == i64::from(seq)
});
match found {
Some(h) => {
removed.push(WithheldRelation {
relation_type: h.relation_type.clone(),
version_id: h.version_id.to_string(),
content_hash: hex::encode(&h.content_hash),
});
false
}
None => true,
}
});
(!removed.is_empty()).then_some(Withheld { relations: removed })
}

/// An edge as returned by `POST …/relations`.
#[derive(Debug, Serialize, JsonSchema)]
pub struct RelationDto {
Expand Down Expand Up @@ -423,6 +503,7 @@ async fn add(
target,
body.attrs.as_ref(),
(Some(id.user_id), Some(id.token_id)),
&caller_ns,
)
.await?;
Ok((StatusCode::CREATED, Json(edge.into())))
Expand Down
21 changes: 14 additions & 7 deletions crates/evalhub-server/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use axum::body::{Body, to_bytes};
use axum::http::{Method, Request, StatusCode, header};
use serde_json::{Value, json};
use testcontainers_modules::postgres::Postgres;
use testcontainers_modules::testcontainers::core::{ContainerPort, ExecCommand, WaitFor};
use testcontainers_modules::testcontainers::core::{ContainerPort, ExecCommand, Mount, WaitFor};
use testcontainers_modules::testcontainers::runners::AsyncRunner;
use testcontainers_modules::testcontainers::{ContainerAsync, GenericImage, ImageExt};
use tower::ServiceExt;
Expand All @@ -39,13 +39,16 @@ pub struct Hub {
pub path_tables: evalhub_server::state::PathTableHandle,
}

/// MinIO image. `minio/minio` on Docker Hub is no longer pullable; the
/// same builds are published on quay.io, and
/// MinIO image. Neither `minio/minio` on Docker Hub nor
/// `quay.io/minio/minio` can be pulled anonymously any more (quay.io
/// started answering `401` in September 2026), so the Chainguard build is
/// used. It ships `mc` and a shell, which the bucket setup below needs.
/// `testcontainers_modules::minio` hard-codes the Docker Hub name, so a
/// `GenericImage` is used instead.
pub const MINIO_IMAGE: &str = "quay.io/minio/minio";
/// Tag matching the one `testcontainers_modules` 0.15 pins.
pub const MINIO_TAG: &str = "RELEASE.2025-02-28T09-55-16Z";
pub const MINIO_IMAGE: &str = "cgr.dev/chainguard/minio";
/// Pinned by digest: Chainguard's free tier publishes `latest` only.
pub const MINIO_TAG: &str =
"latest@sha256:bd014394a80898e68c149f2311fdf8d5a2c2f3bb2c33b9327ae6d02b4b065ae1";
/// Bucket the tests use.
pub const BUCKET: &str = "evalhub";
const MINIO_USER: &str = "minioadmin";
Expand Down Expand Up @@ -229,7 +232,11 @@ pub fn with_title(record: &str, title: &str) -> String {
async fn start_minio() -> (ContainerAsync<GenericImage>, String) {
let container = GenericImage::new(MINIO_IMAGE, MINIO_TAG)
.with_exposed_port(ContainerPort::Tcp(9000))
.with_wait_for(WaitFor::message_on_stderr("API:"))
// `/data` is not a volume in this image; on the container's overlay
// root MinIO logs a rename error, itself starting with "API:", before
// it is up. A tmpfs avoids the error, and the wait names the banner.
.with_wait_for(WaitFor::message_on_stderr("API: http"))
.with_mount(Mount::tmpfs_mount("/data"))
.with_env_var("MINIO_ROOT_USER", MINIO_USER)
.with_env_var("MINIO_ROOT_PASSWORD", MINIO_PASSWORD)
.with_cmd(["server", "/data", "--console-address", ":9001"])
Expand Down
Loading
Loading
0