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
162 changes: 152 additions & 10 deletions crates/twigpine-node/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,26 +46,168 @@ pub(crate) async fn authorize_repo_read(
caller: Option<&str>,
path: &str,
) -> Result<(RepoRecord, Vec<VisibilityRule>)> {
let record = state
let (record, rules) = state
.db
.get_repo(owner, name)
.get_repo_read_policy(owner, name)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
// A quarantined mirror (admitted by the iCaptcha propagation gate but not
// validated) is hidden from every reader — serve/clone and fork alike — as if
// it did not exist, until an operator releases it. Checked before the
// visibility gate so its existence is never disclosed.
if state.db.is_repo_quarantined(&record.id).await? {
return Err(AppError::RepoNotFound(format!("{owner}/{name}")));
}
let rules = state.db.list_visibility_rules(&record.id).await?;
if visibility_check(&rules, record.is_public, &record.owner_did, caller, path) == Decision::Deny
{
return Err(AppError::RepoNotFound(format!("{owner}/{name}")));
}
Ok((record, rules))
}

#[cfg(test)]
mod repo_read_tests {
use super::*;
use crate::db::VisibilityMode;
use axum::body::to_bytes;
use axum::http::StatusCode;
use axum::response::IntoResponse;

async fn authorize_repo_read_sequential(
state: &AppState,
owner: &str,
name: &str,
caller: Option<&str>,
path: &str,
) -> Result<(RepoRecord, Vec<VisibilityRule>)> {
let record = state
.db
.get_repo(owner, name)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;
if state.db.is_repo_quarantined(&record.id).await? {
return Err(AppError::RepoNotFound(format!("{owner}/{name}")));
}
let rules = state.db.list_visibility_rules(&record.id).await?;
if visibility_check(&rules, record.is_public, &record.owner_did, caller, path)
== Decision::Deny
{
return Err(AppError::RepoNotFound(format!("{owner}/{name}")));
}
Ok((record, rules))
}

async fn not_found(err: AppError) -> axum::body::Bytes {
let response = err.into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
to_bytes(response.into_body(), 1024).await.unwrap()
}

#[sqlx::test]
async fn repo_read_gate_matches_sequential_lookup(pool: sqlx::PgPool) {
let state = crate::test_support::test_state(pool).await;
let owner = "did:key:zGateOwner";
let short = "zGateOwner";
let reader = "did:key:zGateReader";
let name = "read-gate";

let missing = not_found(
authorize_repo_read(&state, short, name, None, "/")
.await
.unwrap_err(),
)
.await;
assert_eq!(
not_found(
authorize_repo_read_sequential(&state, short, name, None, "/")
.await
.unwrap_err()
)
.await,
missing,
);

state
.db
.upsert_mirror_repo(short, name, "/srv/mirror", None, false)
.await
.unwrap();
let mirror = authorize_repo_read(&state, short, name, None, "/")
.await
.unwrap();
assert_eq!(mirror.0.id, format!("{short}/{name}"));
assert!(mirror.1.is_empty());
let legacy = authorize_repo_read_sequential(&state, short, name, None, "/")
.await
.unwrap();
assert_eq!(
serde_json::to_value(mirror).unwrap(),
serde_json::to_value(legacy).unwrap()
);

let now = chrono::Utc::now();
let record = RepoRecord {
id: uuid::Uuid::new_v4().to_string(),
name: name.into(),
owner_did: owner.into(),
description: Some("canonical repo".into()),
is_public: true,
default_branch: "main".into(),
created_at: now,
updated_at: now,
disk_path: "/srv/canonical".into(),
forked_from: None,
machine_id: None,
};
state.db.create_repo(&record).await.unwrap();
state
.db
.set_visibility_rule(
&record.id,
"/secret/**",
VisibilityMode::B,
&[reader.into()],
owner,
)
.await
.unwrap();
state
.db
.set_visibility_rule(&record.id, "/secret", VisibilityMode::B, &[], owner)
.await
.unwrap();

for (caller, path, allowed) in [
(None, "/", true),
(None, "/secret/file", false),
(Some(reader), "/secret/file", true),
(Some(short), "/secret/file", true),
(Some("did:web:zGateOwner"), "/secret/file", false),
] {
let before = authorize_repo_read_sequential(&state, short, name, caller, path).await;
let after = authorize_repo_read(&state, short, name, caller, path).await;
assert_eq!(after.is_ok(), allowed, "{caller:?} at {path}");
if allowed {
let after = after.unwrap();
assert_eq!(after.0.id, record.id);
assert_eq!(after.1.len(), 2);
assert_eq!(
serde_json::to_value(after).unwrap(),
serde_json::to_value(before.unwrap()).unwrap()
);
} else {
assert_eq!(not_found(after.unwrap_err()).await, missing);
assert_eq!(not_found(before.unwrap_err()).await, missing);
}
}

state
.db
.set_repo_quarantine(&record.id, true)
.await
.unwrap();
for caller in [None, Some(owner)] {
let before = authorize_repo_read_sequential(&state, short, name, caller, "/").await;
let after = authorize_repo_read(&state, short, name, caller, "/").await;
assert_eq!(not_found(after.unwrap_err()).await, missing);
assert_eq!(not_found(before.unwrap_err()).await, missing);
}
}
}

/// Match a presented DID against a stored DID that may be the full `did:key:<id>`
/// form or the bare `<id>` short form (mirror rows store the bare key). Collapse
/// representation only within `did:key`; never let a bare id match across methods —
Expand Down
112 changes: 78 additions & 34 deletions crates/twigpine-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,34 @@ pub struct VisibilityRule {
pub created_at: DateTime<Utc>,
}

#[derive(Deserialize, sqlx::FromRow)]
struct StoredVisibilityRule {
id: String,
repo_id: String,
path_glob: String,
mode: String,
reader_dids: String,
created_by: String,
created_at: String,
}

impl From<StoredVisibilityRule> for VisibilityRule {
fn from(row: StoredVisibilityRule) -> Self {
Self {
id: row.id,
repo_id: row.repo_id,
path_glob: row.path_glob,
mode: VisibilityMode::from_db(&row.mode),
reader_dids: serde_json::from_str(&row.reader_dids).unwrap_or_default(),
created_by: row.created_by,
created_at: row
.created_at
.parse::<DateTime<Utc>>()
.unwrap_or_else(|_| Utc::now()),
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequest {
pub id: String,
Expand Down Expand Up @@ -3333,6 +3361,22 @@ pub(crate) fn canonical_did(did: &str) -> std::borrow::Cow<'_, str> {
/// drift apart. If you change `normalize_owner_key`, update this const too.
const OWNER_KEY_CASE_SQL: &str = "CASE WHEN owner_did LIKE 'did:key:%' AND position(':' in substr(owner_did, 9)) = 0 THEN substr(owner_did, 9) ELSE owner_did END";

const REPO_RECORD_COLUMNS: &str = "id, name, owner_did, description, is_public, default_branch,
created_at, updated_at, disk_path, forked_from, machine_id";

fn canonical_repo_sql(columns: &str) -> String {
format!(
"SELECT {columns}
FROM repos
WHERE ({OWNER_KEY_CASE_SQL}) = $1
AND name = $2
-- A public mirror must never win over a canonical row.
ORDER BY CASE WHEN position('/' in id) > 0 THEN 1 ELSE 0 END,
created_at ASC, id ASC
LIMIT 1"
)
}

/// `OWNER_KEY_CASE_SQL` over an arbitrary owner column. The const above hardcodes
/// `owner_did` (the `repos` column the `idx_repos_owner_key_name` index is built
/// on); the bounty tombstone needs the same normalizer over `bounties.repo_owner`,
Expand Down Expand Up @@ -3786,21 +3830,7 @@ impl Db {
// `z...` interchangeable while `did:gitlawb:z...` / `did:web:z...` stay
// distinct — the old LIKE '%:' || $1 || '%' was too broad (issue #124 P2).
let owner_key = normalize_owner_key(owner_did);
let sql = format!(
"SELECT id, name, owner_did, description, is_public, default_branch,
created_at, updated_at, disk_path, forked_from, machine_id
FROM repos
WHERE ({key}) = $1
AND name = $2
-- Prefer canonical rows (UUID id, no slash) over mirror rows (slash id).
-- Mirror rows are inserted by upsert_mirror_repo with is_public=true and
-- no visibility rules; using them for visibility checks would bypass the
-- canonical row's gate (issue #124).
ORDER BY CASE WHEN position('/' in id) > 0 THEN 1 ELSE 0 END,
created_at ASC, id ASC
LIMIT 1",
key = OWNER_KEY_CASE_SQL
);
let sql = canonical_repo_sql(REPO_RECORD_COLUMNS);
let row = sqlx::query(&sql)
.bind(owner_key)
.bind(name)
Expand All @@ -3810,6 +3840,37 @@ impl Db {
Ok(row.map(row_to_repo))
}

pub(crate) async fn get_repo_read_policy(
&self,
owner_did: &str,
name: &str,
) -> Result<Option<(RepoRecord, Vec<VisibilityRule>)>> {
let canonical = canonical_repo_sql(&format!("{REPO_RECORD_COLUMNS}, quarantined"));
// Filter quarantine after LIMIT: removing rows earlier could let a mirror win.
let sql = format!(
"SELECT repo.*, (
SELECT COALESCE(json_agg(rule ORDER BY rule.path_glob), '[]')
FROM visibility_rules AS rule WHERE rule.repo_id = repo.id
) AS rules
FROM ({canonical}) AS repo
WHERE NOT repo.quarantined"
);
let row = sqlx::query(&sql)
.bind(normalize_owner_key(owner_did))
.bind(name)
.fetch_optional(&self.pool)
.await?;
let Some(row) = row else {
return Ok(None);
};
let sqlx::types::Json(rules) =
row.try_get::<sqlx::types::Json<Vec<StoredVisibilityRule>>, _>("rules")?;
Ok(Some((
row_to_repo(row),
rules.into_iter().map(VisibilityRule::from).collect(),
)))
}

/// The owner-set homepage of one repo, or `None` when unset or the id is
/// unknown. Read separately from `RepoRecord` so the many repo queries do
/// not carry a column most callers never use.
Expand Down Expand Up @@ -11894,31 +11955,14 @@ impl Db {
}

pub async fn list_visibility_rules(&self, repo_id: &str) -> Result<Vec<VisibilityRule>> {
let rows = sqlx::query(
let rows = sqlx::query_as::<_, StoredVisibilityRule>(
"SELECT id, repo_id, path_glob, mode, reader_dids, created_by, created_at
FROM visibility_rules WHERE repo_id = $1 ORDER BY path_glob",
)
.bind(repo_id)
.fetch_all(&self.pool)
.await?;
Ok(rows
.into_iter()
.map(|r| {
let readers: String = r.get("reader_dids");
let created_at: String = r.get("created_at");
VisibilityRule {
id: r.get("id"),
repo_id: r.get("repo_id"),
path_glob: r.get("path_glob"),
mode: VisibilityMode::from_db(&r.get::<String, _>("mode")),
reader_dids: serde_json::from_str(&readers).unwrap_or_default(),
created_by: r.get("created_by"),
created_at: created_at
.parse::<DateTime<Utc>>()
.unwrap_or_else(|_| Utc::now()),
}
})
.collect())
Ok(rows.into_iter().map(VisibilityRule::from).collect())
}

/// All visibility rules for a set of repos, grouped by `repo_id`, in one
Expand Down