Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: path-scoped repository visibility (Phase 1)
Implements per-path read visibility for repositories, addressing #18.
A repo's private status becomes a property of a path subtree rather
than a whole-repo boolean, enforced on the git read path via the node's
existing DID identity and RFC 9421 HTTP signatures.

Phase 1 scope (whole-repo enforcement, data model for the rest):
- visibility_rules data model (path_glob, mode, reader_dids) + DB access
- visibility_check pure decision function (owner-always-allow, most-
  specific rule wins, reader-DID allow-list, is_public fallback)
- enforcement on git_info_refs and git_upload_pack: unauthorized reads
  return 404 byte-identical to a missing repo (no existence leak)
- owner-only management API: PUT/DELETE/GET /api/v1/repos/{o}/{r}/visibility
- gl visibility set/remove/list CLI

mode A (hide) is whole-repo ("/") only by construction: hiding a
subtree's existence would rewrite ancestor tree hashes and diverge
history. Subtrees use mode B (content withheld, SHAs intact); B-subtree
clone filtering is deferred to a later phase and the CLI/API say so.

260 tests (69 node + 191 gl); fmt + clippy clean.
  • Loading branch information
beardthelion committed Jun 4, 2026
commit b5fc7dd5bc04d01fb19a55e15eb5de3e769a538e
1 change: 1 addition & 0 deletions crates/gitlawb-node/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ pub mod repos;
pub mod resolve;
pub mod stars;
pub mod tasks;
pub mod visibility;
pub mod webhooks;
25 changes: 25 additions & 0 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::cert;
use crate::error::{AppError, Result};
use crate::git::{smart_http, store};
use crate::state::AppState;
use crate::visibility::{visibility_check, Decision};
use crate::webhooks;

// ── Request / Response types ───────────────────────────────────────────────
Expand Down Expand Up @@ -308,6 +309,7 @@ pub async fn git_info_refs(
State(state): State<AppState>,
Path((owner, repo)): Path<(String, String)>,
Query(query): Query<InfoRefsQuery>,
auth: Option<Extension<AuthenticatedDid>>,
) -> Result<Response> {
let name = repo.trim_end_matches(".git");
tracing::info!(owner = %owner, repo = %name, "info/refs request");
Expand All @@ -322,6 +324,20 @@ pub async fn git_info_refs(
.ok_or_else(|| AppError::BadRequest("missing ?service= parameter".into()))?;
tracing::debug!(service = %service, repo = %name, "info/refs service");

// Enforce read (clone/fetch) visibility. The push advertisement
// (service=git-receive-pack) is authorized separately on the
// git-receive-pack POST, so leave it untouched here.
if service == "git-upload-pack" {
let rules = state.db.list_visibility_rules(&record.id).await?;
let caller = auth.as_ref().map(|e| e.0 .0.as_str());
if visibility_check(&rules, record.is_public, &record.owner_did, caller, "/")
== Decision::Deny
{
tracing::debug!(repo = %name, caller = ?caller, "info/refs read denied by visibility");
return Err(AppError::RepoNotFound(format!("{owner}/{name}")));
}
}

// For receive-pack (push), download the latest from Tigris so the client
// sees the same refs that acquire_write() will operate on.
let disk_path = if service == "git-receive-pack" {
Expand Down Expand Up @@ -352,6 +368,7 @@ pub async fn git_info_refs(
pub async fn git_upload_pack(
State(state): State<AppState>,
Path((owner, repo)): Path<(String, String)>,
auth: Option<Extension<AuthenticatedDid>>,
body: Bytes,
) -> Result<Response> {
let name = repo.trim_end_matches(".git");
Expand All @@ -361,6 +378,14 @@ pub async fn git_upload_pack(
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{name}")))?;

let rules = state.db.list_visibility_rules(&record.id).await?;
let caller = auth.as_ref().map(|e| e.0 .0.as_str());
if visibility_check(&rules, record.is_public, &record.owner_did, caller, "/") == Decision::Deny
{
tracing::debug!(repo = %name, caller = ?caller, "upload-pack read denied by visibility");
return Err(AppError::RepoNotFound(format!("{owner}/{name}")));
}

let disk_path = state
.repo_store
.acquire(&record.owner_did, &record.name)
Expand Down
159 changes: 159 additions & 0 deletions crates/gitlawb-node/src/api/visibility.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! Path-scoped visibility management API. Owner-only, mirrors `api/protect.rs`.

use axum::extract::{Extension, Path, State};
use axum::http::StatusCode;
use axum::Json;
use serde::Deserialize;

use crate::auth::AuthenticatedDid;
use crate::db::VisibilityMode;
use crate::error::{AppError, Result};
use crate::state::AppState;

#[derive(Deserialize)]
pub struct SetVisibilityRequest {
pub path_glob: String,
/// "a" or "b"; defaults to "b" if absent or unrecognized.
#[serde(default)]
pub mode: Option<String>,
#[serde(default)]
pub reader_dids: Vec<String>,
}

#[derive(Deserialize)]
pub struct RemoveVisibilityRequest {
pub path_glob: String,
}

fn require_owner(record: &crate::db::RepoRecord, caller: &str) -> Result<()> {
let owner_short = record
.owner_did
.split(':')
.next_back()
.unwrap_or(&record.owner_did);
if caller != record.owner_did && caller != owner_short {
return Err(AppError::BadRequest(
"only the repo owner can manage visibility".into(),
));
}
Ok(())
}

/// PUT /api/v1/repos/{owner}/{repo}/visibility
pub async fn set_visibility(
State(state): State<AppState>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, repo)): Path<(String, String)>,
Json(req): Json<SetVisibilityRequest>,
) -> Result<(StatusCode, Json<serde_json::Value>)> {
let record = state
.db
.get_repo(&owner, &repo)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
require_owner(&record, &auth.0)?;

let mode = match req.mode.as_deref() {
Some("a") => VisibilityMode::A,
_ => VisibilityMode::B,
};

// Mode A hides existence and is only coherent for the whole repo; a subtree
// cannot hide its existence without rewriting git history (see spec).
if mode == VisibilityMode::A && req.path_glob != "/" {
return Err(AppError::BadRequest(
"mode 'a' (hide) is only allowed for the whole repo (path_glob '/'); use mode 'b' for subtrees".into(),
));
}

// An empty reader_dids list is valid and intentional: the owner is always
// allowed by visibility_check, so a "/" rule with no readers is exactly the
// whole-repo "private to owner only" case.
state
.db
.set_visibility_rule(&record.id, &req.path_glob, mode, &req.reader_dids, &auth.0)
.await?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

let subtree_warning = req.path_glob != "/";
tracing::info!(
repo = %repo, caller = %auth.0, path_glob = %req.path_glob, mode = %mode.as_str(),
subtree_pending = subtree_warning,
"visibility rule set"
);

Ok((
StatusCode::CREATED,
Json(serde_json::json!({
"status": "set",
"repo": format!("{owner}/{repo}"),
"path_glob": req.path_glob,
"mode": mode.as_str(),
"reader_dids": req.reader_dids,
"subtree_clone_enforcement_pending": subtree_warning,
})),
))
}

/// DELETE /api/v1/repos/{owner}/{repo}/visibility
pub async fn remove_visibility(
State(state): State<AppState>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, repo)): Path<(String, String)>,
Json(req): Json<RemoveVisibilityRequest>,
) -> Result<Json<serde_json::Value>> {
let record = state
.db
.get_repo(&owner, &repo)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
require_owner(&record, &auth.0)?;

state
.db
.remove_visibility_rule(&record.id, &req.path_glob)
.await?;

tracing::info!(
repo = %repo, caller = %auth.0, path_glob = %req.path_glob,
"visibility rule removed"
);

Ok(Json(serde_json::json!({
"status": "removed",
"repo": format!("{owner}/{repo}"),
"path_glob": req.path_glob,
})))
}

/// GET /api/v1/repos/{owner}/{repo}/visibility
pub async fn list_visibility(
State(state): State<AppState>,
Extension(auth): Extension<AuthenticatedDid>,
Path((owner, repo)): Path<(String, String)>,
) -> Result<Json<serde_json::Value>> {
let record = state
.db
.get_repo(&owner, &repo)
.await?
.ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}")))?;
require_owner(&record, &auth.0)?;

let rules = state.db.list_visibility_rules(&record.id).await?;
let rules_json: Vec<_> = rules
.into_iter()
.map(|r| {
serde_json::json!({
"path_glob": r.path_glob,
"mode": r.mode.as_str(),
"reader_dids": r.reader_dids,
"created_by": r.created_by,
})
})
.collect();

Ok(Json(serde_json::json!({
"repo": format!("{owner}/{repo}"),
"count": rules_json.len(),
"rules": rules_json,
})))
}
131 changes: 131 additions & 0 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,51 @@ pub struct RepoRecord {
pub machine_id: Option<String>,
}

/// Per-rule replication mode for a visibility rule.
/// `A` hides existence entirely (only valid at whole-repo scope `/`).
/// `B` keeps object SHAs and the path visible but withholds content
/// (the only mode allowed for subtrees; enforced on clones in Phase 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VisibilityMode {
A,
B,
}

impl VisibilityMode {
pub fn as_str(&self) -> &'static str {
match self {
VisibilityMode::A => "a",
VisibilityMode::B => "b",
}
}

pub fn from_db(s: &str) -> Self {
match s {
"a" => VisibilityMode::A,
"b" => VisibilityMode::B,
other => {
tracing::warn!("unknown visibility mode in DB: {other:?}, defaulting to B");
VisibilityMode::B
}
}
}
}

/// A path-scoped visibility rule. `path_glob` is "/" for whole-repo, or a
/// subtree pattern such as "/secret-pkg/**". The repo owner is always an
/// implicit reader regardless of `reader_dids`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisibilityRule {
pub id: String,
pub repo_id: String,
pub path_glob: String,
pub mode: VisibilityMode,
pub reader_dids: Vec<String>,
pub created_by: String,
pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequest {
pub id: String,
Expand Down Expand Up @@ -564,6 +609,18 @@ const MIGRATIONS: &[Migration] = &[
UNIQUE(repo_id, branch)
)"#,
"CREATE INDEX IF NOT EXISTS idx_protected_branches_repo ON protected_branches(repo_id)",
// ── Path-scoped visibility ────────────────────────────────────────
r#"CREATE TABLE IF NOT EXISTS visibility_rules (
id TEXT NOT NULL PRIMARY KEY,
repo_id TEXT NOT NULL,
path_glob TEXT NOT NULL,
mode TEXT NOT NULL,
reader_dids TEXT NOT NULL,
created_by TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(repo_id, path_glob)
)"#,
"CREATE INDEX IF NOT EXISTS idx_visibility_rules_repo ON visibility_rules(repo_id)",
// ── Repo stars ──────────────────────────────────────────────────
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
r#"CREATE TABLE IF NOT EXISTS repo_stars (
id TEXT NOT NULL PRIMARY KEY,
Expand Down Expand Up @@ -2072,6 +2129,80 @@ impl Db {
}
}

// ── Path-scoped Visibility ────────────────────────────────────────────────────

impl Db {
pub async fn set_visibility_rule(
&self,
repo_id: &str,
path_glob: &str,
mode: VisibilityMode,
reader_dids: &[String],
created_by: &str,
) -> Result<()> {
let id = Uuid::new_v4().to_string();
let now = Utc::now().to_rfc3339();
let readers = serde_json::to_string(reader_dids).unwrap_or_else(|_| "[]".to_string());
sqlx::query(
"INSERT INTO visibility_rules
(id, repo_id, path_glob, mode, reader_dids, created_by, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (repo_id, path_glob) DO UPDATE
SET mode = EXCLUDED.mode,
reader_dids = EXCLUDED.reader_dids,
created_by = EXCLUDED.created_by,
created_at = EXCLUDED.created_at",
)
.bind(&id)
.bind(repo_id)
.bind(path_glob)
.bind(mode.as_str())
.bind(&readers)
.bind(created_by)
.bind(&now)
.execute(&self.pool)
.await?;
Ok(())
}

pub async fn remove_visibility_rule(&self, repo_id: &str, path_glob: &str) -> Result<()> {
sqlx::query("DELETE FROM visibility_rules WHERE repo_id = $1 AND path_glob = $2")
.bind(repo_id)
.bind(path_glob)
.execute(&self.pool)
.await?;
Ok(())
}

pub async fn list_visibility_rules(&self, repo_id: &str) -> Result<Vec<VisibilityRule>> {
let rows = sqlx::query(
"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())
}
}

// ── Repo Stars ────────────────────────────────────────────────────────────────

impl Db {
Expand Down
1 change: 1 addition & 0 deletions crates/gitlawb-node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod rate_limit;
mod server;
mod state;
mod sync;
mod visibility;
mod webhooks;

use anyhow::{Context, Result};
Expand Down
Loading