diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/git/handlers.rs | 47 | ||||
| -rw-r--r-- | src/git/mod.rs | 273 | ||||
| -rw-r--r-- | src/nostr/builder.rs | 280 | ||||
| -rw-r--r-- | src/nostr/events.rs | 174 |
4 files changed, 764 insertions, 10 deletions
diff --git a/src/git/handlers.rs b/src/git/handlers.rs index 27bec76..73f72f3 100644 --- a/src/git/handlers.rs +++ b/src/git/handlers.rs | |||
| @@ -13,6 +13,9 @@ use super::authorization::{ | |||
| 13 | }; | 13 | }; |
| 14 | use super::protocol::{GitService, PktLine}; | 14 | use super::protocol::{GitService, PktLine}; |
| 15 | use super::subprocess::GitSubprocess; | 15 | use super::subprocess::GitSubprocess; |
| 16 | use super::{try_set_head_if_available}; | ||
| 17 | |||
| 18 | use crate::nostr::events::RepositoryState; | ||
| 16 | 19 | ||
| 17 | /// Handle GET /info/refs?service=git-{upload,receive}-pack | 20 | /// Handle GET /info/refs?service=git-{upload,receive}-pack |
| 18 | /// | 21 | /// |
| @@ -163,6 +166,9 @@ pub struct PushAuthParams { | |||
| 163 | /// This includes GRASP authorization validation according to GRASP-01: | 166 | /// This includes GRASP authorization validation according to GRASP-01: |
| 164 | /// "MUST accept pushes via this service that match the latest repo state announcement | 167 | /// "MUST accept pushes via this service that match the latest repo state announcement |
| 165 | /// on the relay, respecting the recursive maintainer set." | 168 | /// on the relay, respecting the recursive maintainer set." |
| 169 | /// | ||
| 170 | /// Also per GRASP-01: "MUST set repository HEAD per repository state announcement | ||
| 171 | /// as soon as the git data related to that branch has been received." | ||
| 166 | pub async fn handle_receive_pack( | 172 | pub async fn handle_receive_pack( |
| 167 | repo_path: PathBuf, | 173 | repo_path: PathBuf, |
| 168 | request_body: Bytes, | 174 | request_body: Bytes, |
| @@ -174,14 +180,17 @@ pub async fn handle_receive_pack( | |||
| 174 | return Err(GitError::RepositoryNotFound); | 180 | return Err(GitError::RepositoryNotFound); |
| 175 | } | 181 | } |
| 176 | 182 | ||
| 183 | // Keep track of state for HEAD setting after push | ||
| 184 | let mut authorized_state: Option<RepositoryState> = None; | ||
| 185 | |||
| 177 | // GRASP Authorization Check | 186 | // GRASP Authorization Check |
| 178 | if let Some(params) = auth_params { | 187 | if let Some(ref params) = auth_params { |
| 179 | info!( | 188 | info!( |
| 180 | "Authorizing push for {}/{} via {}", | 189 | "Authorizing push for {}/{} via {}", |
| 181 | params.owner_npub, params.identifier, params.relay_url | 190 | params.owner_npub, params.identifier, params.relay_url |
| 182 | ); | 191 | ); |
| 183 | 192 | ||
| 184 | match authorize_push(¶ms, &request_body).await { | 193 | match authorize_push(params, &request_body).await { |
| 185 | Ok(auth_result) => { | 194 | Ok(auth_result) => { |
| 186 | if !auth_result.authorized { | 195 | if !auth_result.authorized { |
| 187 | warn!( | 196 | warn!( |
| @@ -196,6 +205,8 @@ pub async fn handle_receive_pack( | |||
| 196 | params.identifier, | 205 | params.identifier, |
| 197 | auth_result.maintainers.len() | 206 | auth_result.maintainers.len() |
| 198 | ); | 207 | ); |
| 208 | // Save the state for HEAD setting after push | ||
| 209 | authorized_state = auth_result.state; | ||
| 199 | } | 210 | } |
| 200 | Err(e) => { | 211 | Err(e) => { |
| 201 | warn!( | 212 | warn!( |
| @@ -246,6 +257,38 @@ pub async fn handle_receive_pack( | |||
| 246 | return Err(GitError::GitFailed(status.code())); | 257 | return Err(GitError::GitFailed(status.code())); |
| 247 | } | 258 | } |
| 248 | 259 | ||
| 260 | // GRASP-01: Set HEAD after git data is received | ||
| 261 | // "MUST set repository HEAD per repository state announcement | ||
| 262 | // as soon as the git data related to that branch has been received." | ||
| 263 | if let Some(state) = authorized_state { | ||
| 264 | if let Some(head_ref) = &state.head { | ||
| 265 | if let Some(branch_name) = state.get_head_branch() { | ||
| 266 | if let Some(commit) = state.get_branch_commit(branch_name) { | ||
| 267 | match try_set_head_if_available(&repo_path, head_ref, commit) { | ||
| 268 | Ok(true) => { | ||
| 269 | info!( | ||
| 270 | "Set HEAD to {} after push to {:?}", | ||
| 271 | head_ref, repo_path | ||
| 272 | ); | ||
| 273 | } | ||
| 274 | Ok(false) => { | ||
| 275 | debug!( | ||
| 276 | "HEAD commit {} not found after push, HEAD not updated", | ||
| 277 | commit | ||
| 278 | ); | ||
| 279 | } | ||
| 280 | Err(e) => { | ||
| 281 | warn!( | ||
| 282 | "Failed to set HEAD after push: {}", | ||
| 283 | e | ||
| 284 | ); | ||
| 285 | } | ||
| 286 | } | ||
| 287 | } | ||
| 288 | } | ||
| 289 | } | ||
| 290 | } | ||
| 291 | |||
| 249 | Ok(Response::builder() | 292 | Ok(Response::builder() |
| 250 | .status(StatusCode::OK) | 293 | .status(StatusCode::OK) |
| 251 | .header("content-type", GitService::ReceivePack.result_content_type()) | 294 | .header("content-type", GitService::ReceivePack.result_content_type()) |
diff --git a/src/git/mod.rs b/src/git/mod.rs index 81ff277..076e211 100644 --- a/src/git/mod.rs +++ b/src/git/mod.rs | |||
| @@ -22,7 +22,9 @@ pub mod handlers; | |||
| 22 | pub mod protocol; | 22 | pub mod protocol; |
| 23 | pub mod subprocess; | 23 | pub mod subprocess; |
| 24 | 24 | ||
| 25 | use std::path::PathBuf; | 25 | use std::path::{Path, PathBuf}; |
| 26 | use std::process::Command; | ||
| 27 | use tracing::{debug, info}; | ||
| 26 | 28 | ||
| 27 | /// Parse a Git repository path from URL components | 29 | /// Parse a Git repository path from URL components |
| 28 | /// | 30 | /// |
| @@ -44,6 +46,130 @@ pub fn resolve_repo_path(git_data_path: &str, npub: &str, identifier: &str) -> P | |||
| 44 | .join(format!("{}.git", identifier)) | 46 | .join(format!("{}.git", identifier)) |
| 45 | } | 47 | } |
| 46 | 48 | ||
| 49 | /// Check if a commit exists in the repository | ||
| 50 | /// | ||
| 51 | /// # Arguments | ||
| 52 | /// * `repo_path` - Path to the bare git repository | ||
| 53 | /// * `commit_hash` - The commit hash to check | ||
| 54 | /// | ||
| 55 | /// # Returns | ||
| 56 | /// True if the commit exists in the repository, false otherwise | ||
| 57 | pub fn commit_exists(repo_path: &Path, commit_hash: &str) -> bool { | ||
| 58 | let output = Command::new("git") | ||
| 59 | .args(["cat-file", "-t", commit_hash]) | ||
| 60 | .current_dir(repo_path) | ||
| 61 | .output(); | ||
| 62 | |||
| 63 | match output { | ||
| 64 | Ok(result) => { | ||
| 65 | if result.status.success() { | ||
| 66 | let obj_type = String::from_utf8_lossy(&result.stdout); | ||
| 67 | // Object exists and is a commit | ||
| 68 | obj_type.trim() == "commit" | ||
| 69 | } else { | ||
| 70 | false | ||
| 71 | } | ||
| 72 | } | ||
| 73 | Err(_) => false, | ||
| 74 | } | ||
| 75 | } | ||
| 76 | |||
| 77 | /// Set the repository HEAD to point to a branch | ||
| 78 | /// | ||
| 79 | /// This updates the HEAD symbolic ref to point to the specified branch. | ||
| 80 | /// Per GRASP-01: "MUST set repository HEAD per repository state announcement | ||
| 81 | /// as soon as the git data related to that branch has been received." | ||
| 82 | /// | ||
| 83 | /// # Arguments | ||
| 84 | /// * `repo_path` - Path to the bare git repository | ||
| 85 | /// * `head_ref` - The ref to set HEAD to (e.g., "refs/heads/main") | ||
| 86 | /// | ||
| 87 | /// # Returns | ||
| 88 | /// Ok(()) if successful, Err with error message otherwise | ||
| 89 | pub fn set_repository_head(repo_path: &Path, head_ref: &str) -> Result<(), String> { | ||
| 90 | // Validate the ref format | ||
| 91 | if !head_ref.starts_with("refs/heads/") { | ||
| 92 | return Err(format!("Invalid HEAD ref: {} (must start with refs/heads/)", head_ref)); | ||
| 93 | } | ||
| 94 | |||
| 95 | debug!("Setting HEAD to {} in {}", head_ref, repo_path.display()); | ||
| 96 | |||
| 97 | let output = Command::new("git") | ||
| 98 | .args(["symbolic-ref", "HEAD", head_ref]) | ||
| 99 | .current_dir(repo_path) | ||
| 100 | .output() | ||
| 101 | .map_err(|e| format!("Failed to execute git symbolic-ref: {}", e))?; | ||
| 102 | |||
| 103 | if !output.status.success() { | ||
| 104 | let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 105 | return Err(format!("git symbolic-ref failed: {}", stderr)); | ||
| 106 | } | ||
| 107 | |||
| 108 | info!("Updated HEAD to {} in {}", head_ref, repo_path.display()); | ||
| 109 | Ok(()) | ||
| 110 | } | ||
| 111 | |||
| 112 | /// Try to set repository HEAD from a repository state event | ||
| 113 | /// | ||
| 114 | /// This function checks if the HEAD branch's commit is available in the repository | ||
| 115 | /// and sets HEAD if it is. This should be called: | ||
| 116 | /// 1. When a repository state event is received (in case git data already exists) | ||
| 117 | /// 2. After git data is received (in case a state event was already received) | ||
| 118 | /// | ||
| 119 | /// # Arguments | ||
| 120 | /// * `repo_path` - Path to the bare git repository | ||
| 121 | /// * `head_ref` - The ref to set HEAD to (e.g., "refs/heads/main") | ||
| 122 | /// * `head_commit` - The commit hash that the HEAD branch should point to | ||
| 123 | /// | ||
| 124 | /// # Returns | ||
| 125 | /// Ok(true) if HEAD was set, Ok(false) if commit not yet available, Err on failure | ||
| 126 | pub fn try_set_head_if_available( | ||
| 127 | repo_path: &Path, | ||
| 128 | head_ref: &str, | ||
| 129 | head_commit: &str, | ||
| 130 | ) -> Result<bool, String> { | ||
| 131 | // Check if repository exists | ||
| 132 | if !repo_path.exists() { | ||
| 133 | debug!("Repository not found at {}, cannot set HEAD", repo_path.display()); | ||
| 134 | return Ok(false); | ||
| 135 | } | ||
| 136 | |||
| 137 | // Check if the commit exists in the repository | ||
| 138 | if !commit_exists(repo_path, head_commit) { | ||
| 139 | debug!( | ||
| 140 | "Commit {} not found in {}, HEAD not set yet", | ||
| 141 | head_commit, | ||
| 142 | repo_path.display() | ||
| 143 | ); | ||
| 144 | return Ok(false); | ||
| 145 | } | ||
| 146 | |||
| 147 | // Commit exists, set HEAD | ||
| 148 | set_repository_head(repo_path, head_ref)?; | ||
| 149 | Ok(true) | ||
| 150 | } | ||
| 151 | |||
| 152 | /// Get the current HEAD ref from a repository | ||
| 153 | /// | ||
| 154 | /// # Arguments | ||
| 155 | /// * `repo_path` - Path to the bare git repository | ||
| 156 | /// | ||
| 157 | /// # Returns | ||
| 158 | /// The current HEAD ref (e.g., "refs/heads/main") or None if not set | ||
| 159 | pub fn get_repository_head(repo_path: &Path) -> Option<String> { | ||
| 160 | let output = Command::new("git") | ||
| 161 | .args(["symbolic-ref", "HEAD"]) | ||
| 162 | .current_dir(repo_path) | ||
| 163 | .output() | ||
| 164 | .ok()?; | ||
| 165 | |||
| 166 | if output.status.success() { | ||
| 167 | Some(String::from_utf8_lossy(&output.stdout).trim().to_string()) | ||
| 168 | } else { | ||
| 169 | None | ||
| 170 | } | ||
| 171 | } | ||
| 172 | |||
| 47 | /// Extract npub and identifier from a Git URL path | 173 | /// Extract npub and identifier from a Git URL path |
| 48 | /// | 174 | /// |
| 49 | /// Parses paths like `/<npub>/<identifier>.git/info/refs` | 175 | /// Parses paths like `/<npub>/<identifier>.git/info/refs` |
| @@ -77,6 +203,83 @@ pub fn parse_git_url(path: &str) -> Option<(&str, &str, &str)> { | |||
| 77 | #[cfg(test)] | 203 | #[cfg(test)] |
| 78 | mod tests { | 204 | mod tests { |
| 79 | use super::*; | 205 | use super::*; |
| 206 | use std::fs; | ||
| 207 | use tempfile::TempDir; | ||
| 208 | |||
| 209 | /// Create a test bare repository with optional commits | ||
| 210 | fn create_test_repo() -> (TempDir, PathBuf) { | ||
| 211 | let temp_dir = TempDir::new().unwrap(); | ||
| 212 | let repo_path = temp_dir.path().join("test.git"); | ||
| 213 | |||
| 214 | // Initialize bare repository | ||
| 215 | Command::new("git") | ||
| 216 | .args(["init", "--bare", repo_path.to_str().unwrap()]) | ||
| 217 | .output() | ||
| 218 | .unwrap(); | ||
| 219 | |||
| 220 | (temp_dir, repo_path) | ||
| 221 | } | ||
| 222 | |||
| 223 | /// Create a test repository with a commit on a branch | ||
| 224 | fn create_test_repo_with_commit() -> (TempDir, PathBuf, String) { | ||
| 225 | let temp_dir = TempDir::new().unwrap(); | ||
| 226 | let work_dir = temp_dir.path().join("work"); | ||
| 227 | let bare_repo = temp_dir.path().join("test.git"); | ||
| 228 | |||
| 229 | // Initialize bare repository | ||
| 230 | Command::new("git") | ||
| 231 | .args(["init", "--bare", bare_repo.to_str().unwrap()]) | ||
| 232 | .output() | ||
| 233 | .unwrap(); | ||
| 234 | |||
| 235 | // Clone to working directory | ||
| 236 | Command::new("git") | ||
| 237 | .args(["clone", bare_repo.to_str().unwrap(), work_dir.to_str().unwrap()]) | ||
| 238 | .output() | ||
| 239 | .unwrap(); | ||
| 240 | |||
| 241 | // Configure git for commits | ||
| 242 | Command::new("git") | ||
| 243 | .args(["config", "user.email", "test@test.com"]) | ||
| 244 | .current_dir(&work_dir) | ||
| 245 | .output() | ||
| 246 | .unwrap(); | ||
| 247 | Command::new("git") | ||
| 248 | .args(["config", "user.name", "Test"]) | ||
| 249 | .current_dir(&work_dir) | ||
| 250 | .output() | ||
| 251 | .unwrap(); | ||
| 252 | |||
| 253 | // Create a file and commit | ||
| 254 | fs::write(work_dir.join("README.md"), "# Test").unwrap(); | ||
| 255 | Command::new("git") | ||
| 256 | .args(["add", "README.md"]) | ||
| 257 | .current_dir(&work_dir) | ||
| 258 | .output() | ||
| 259 | .unwrap(); | ||
| 260 | Command::new("git") | ||
| 261 | .args(["commit", "-m", "Initial commit"]) | ||
| 262 | .current_dir(&work_dir) | ||
| 263 | .output() | ||
| 264 | .unwrap(); | ||
| 265 | |||
| 266 | // Get commit hash | ||
| 267 | let output = Command::new("git") | ||
| 268 | .args(["rev-parse", "HEAD"]) | ||
| 269 | .current_dir(&work_dir) | ||
| 270 | .output() | ||
| 271 | .unwrap(); | ||
| 272 | let commit_hash = String::from_utf8_lossy(&output.stdout).trim().to_string(); | ||
| 273 | |||
| 274 | // Push to bare repo | ||
| 275 | Command::new("git") | ||
| 276 | .args(["push", "origin", "master"]) | ||
| 277 | .current_dir(&work_dir) | ||
| 278 | .output() | ||
| 279 | .unwrap(); | ||
| 280 | |||
| 281 | (temp_dir, bare_repo, commit_hash) | ||
| 282 | } | ||
| 80 | 283 | ||
| 81 | #[test] | 284 | #[test] |
| 82 | fn test_resolve_repo_path() { | 285 | fn test_resolve_repo_path() { |
| @@ -125,4 +328,72 @@ mod tests { | |||
| 125 | assert!(parse_git_url("/npub1abc").is_none()); | 328 | assert!(parse_git_url("/npub1abc").is_none()); |
| 126 | assert!(parse_git_url("/npub1abc/repo").is_none()); | 329 | assert!(parse_git_url("/npub1abc/repo").is_none()); |
| 127 | } | 330 | } |
| 331 | |||
| 332 | #[test] | ||
| 333 | fn test_commit_exists_nonexistent() { | ||
| 334 | let (_temp_dir, repo_path) = create_test_repo(); | ||
| 335 | assert!(!commit_exists(&repo_path, "deadbeef1234567890abcdef1234567890abcdef")); | ||
| 336 | } | ||
| 337 | |||
| 338 | #[test] | ||
| 339 | fn test_commit_exists_with_commit() { | ||
| 340 | let (_temp_dir, repo_path, commit_hash) = create_test_repo_with_commit(); | ||
| 341 | assert!(commit_exists(&repo_path, &commit_hash)); | ||
| 342 | } | ||
| 343 | |||
| 344 | #[test] | ||
| 345 | fn test_set_repository_head() { | ||
| 346 | let (_temp_dir, repo_path, _commit_hash) = create_test_repo_with_commit(); | ||
| 347 | |||
| 348 | // Default HEAD might be refs/heads/master | ||
| 349 | let result = set_repository_head(&repo_path, "refs/heads/main"); | ||
| 350 | assert!(result.is_ok()); | ||
| 351 | |||
| 352 | let head = get_repository_head(&repo_path); | ||
| 353 | assert_eq!(head, Some("refs/heads/main".to_string())); | ||
| 354 | } | ||
| 355 | |||
| 356 | #[test] | ||
| 357 | fn test_set_repository_head_invalid_ref() { | ||
| 358 | let (_temp_dir, repo_path) = create_test_repo(); | ||
| 359 | |||
| 360 | // Invalid ref format should fail | ||
| 361 | let result = set_repository_head(&repo_path, "main"); | ||
| 362 | assert!(result.is_err()); | ||
| 363 | assert!(result.unwrap_err().contains("must start with refs/heads/")); | ||
| 364 | } | ||
| 365 | |||
| 366 | #[test] | ||
| 367 | fn test_try_set_head_if_available_commit_missing() { | ||
| 368 | let (_temp_dir, repo_path) = create_test_repo(); | ||
| 369 | |||
| 370 | let result = try_set_head_if_available( | ||
| 371 | &repo_path, | ||
| 372 | "refs/heads/main", | ||
| 373 | "deadbeef1234567890abcdef1234567890abcdef", | ||
| 374 | ); | ||
| 375 | |||
| 376 | // Should return Ok(false) - commit not found | ||
| 377 | assert!(result.is_ok()); | ||
| 378 | assert!(!result.unwrap()); | ||
| 379 | } | ||
| 380 | |||
| 381 | #[test] | ||
| 382 | fn test_try_set_head_if_available_success() { | ||
| 383 | let (_temp_dir, repo_path, commit_hash) = create_test_repo_with_commit(); | ||
| 384 | |||
| 385 | let result = try_set_head_if_available( | ||
| 386 | &repo_path, | ||
| 387 | "refs/heads/main", | ||
| 388 | &commit_hash, | ||
| 389 | ); | ||
| 390 | |||
| 391 | // Should return Ok(true) - HEAD was set | ||
| 392 | assert!(result.is_ok()); | ||
| 393 | assert!(result.unwrap()); | ||
| 394 | |||
| 395 | // Verify HEAD was set | ||
| 396 | let head = get_repository_head(&repo_path); | ||
| 397 | assert_eq!(head, Some("refs/heads/main".to_string())); | ||
| 398 | } | ||
| 128 | } \ No newline at end of file | 399 | } \ No newline at end of file |
diff --git a/src/nostr/builder.rs b/src/nostr/builder.rs index 259c380..285e6f3 100644 --- a/src/nostr/builder.rs +++ b/src/nostr/builder.rs | |||
| @@ -12,8 +12,10 @@ use nostr::{EventId, Filter, Kind, PublicKey}; | |||
| 12 | use nostr_relay_builder::prelude::*; | 12 | use nostr_relay_builder::prelude::*; |
| 13 | 13 | ||
| 14 | use crate::config::{Config, DatabaseBackend}; | 14 | use crate::config::{Config, DatabaseBackend}; |
| 15 | use crate::git; | ||
| 15 | use crate::nostr::events::{ | 16 | use crate::nostr::events::{ |
| 16 | validate_announcement, validate_state, RepositoryAnnouncement, KIND_REPOSITORY_ANNOUNCEMENT, KIND_REPOSITORY_STATE, | 17 | validate_announcement, validate_state, RepositoryAnnouncement, RepositoryState, |
| 18 | KIND_REPOSITORY_ANNOUNCEMENT, KIND_REPOSITORY_STATE, | ||
| 17 | }; | 19 | }; |
| 18 | 20 | ||
| 19 | /// NIP-34 Write Policy with Full GRASP-01 Event Validation | 21 | /// NIP-34 Write Policy with Full GRASP-01 Event Validation |
| @@ -77,6 +79,230 @@ impl Nip34WritePolicy { | |||
| 77 | Ok(()) | 79 | Ok(()) |
| 78 | } | 80 | } |
| 79 | 81 | ||
| 82 | /// Check if this state event is the latest for its identifier among authorized authors | ||
| 83 | /// | ||
| 84 | /// A state is considered "latest" if no other state event in the database | ||
| 85 | /// from an authorized author has a newer timestamp. This handles out-of-order | ||
| 86 | /// delivery where an older event arrives after a newer one. | ||
| 87 | /// | ||
| 88 | /// The authorized_pubkeys should be the owner and maintainers of a specific | ||
| 89 | /// announcement, so different owners with the same identifier don't interfere. | ||
| 90 | async fn is_latest_state_for_identifier( | ||
| 91 | database: &Arc<MemoryDatabase>, | ||
| 92 | state: &RepositoryState, | ||
| 93 | authorized_pubkeys: &[PublicKey], | ||
| 94 | ) -> Result<bool, String> { | ||
| 95 | let filter = Filter::new() | ||
| 96 | .kind(Kind::from(KIND_REPOSITORY_STATE)) | ||
| 97 | .custom_tag( | ||
| 98 | SingleLetterTag::lowercase(Alphabet::D), | ||
| 99 | state.identifier.clone(), | ||
| 100 | ); | ||
| 101 | |||
| 102 | match database.query(filter).await { | ||
| 103 | Ok(events) => { | ||
| 104 | for event in events { | ||
| 105 | // Skip comparing to self (same event ID) | ||
| 106 | if event.id == state.event.id { | ||
| 107 | continue; | ||
| 108 | } | ||
| 109 | // Only consider events from authorized authors for this announcement | ||
| 110 | if !authorized_pubkeys.contains(&event.pubkey) { | ||
| 111 | continue; | ||
| 112 | } | ||
| 113 | // If any existing event from an authorized author is newer, this is not the latest | ||
| 114 | if event.created_at > state.event.created_at { | ||
| 115 | tracing::debug!( | ||
| 116 | "State {} is not latest: found newer state {} from {} (ts {} > {})", | ||
| 117 | state.event.id.to_hex(), | ||
| 118 | event.id.to_hex(), | ||
| 119 | event.pubkey.to_hex(), | ||
| 120 | event.created_at.as_secs(), | ||
| 121 | state.event.created_at.as_secs() | ||
| 122 | ); | ||
| 123 | return Ok(false); | ||
| 124 | } | ||
| 125 | } | ||
| 126 | Ok(true) | ||
| 127 | } | ||
| 128 | Err(e) => Err(format!("Database query failed: {}", e)), | ||
| 129 | } | ||
| 130 | } | ||
| 131 | |||
| 132 | /// Find all repository announcements where the given pubkey is authorized | ||
| 133 | /// | ||
| 134 | /// A pubkey is authorized for an announcement if: | ||
| 135 | /// - They are the owner (pubkey of the announcement event), OR | ||
| 136 | /// - They are listed in the "maintainers" tag | ||
| 137 | /// | ||
| 138 | /// This is needed because a maintainer can publish a state event that | ||
| 139 | /// should update HEAD in the repository of the announcement owner, | ||
| 140 | /// not in the maintainer's own (possibly non-existent) repository. | ||
| 141 | async fn find_authorized_announcements( | ||
| 142 | database: &Arc<MemoryDatabase>, | ||
| 143 | identifier: &str, | ||
| 144 | state_author: &PublicKey, | ||
| 145 | ) -> Result<Vec<RepositoryAnnouncement>, String> { | ||
| 146 | let filter = Filter::new() | ||
| 147 | .kind(Kind::from(KIND_REPOSITORY_ANNOUNCEMENT)) | ||
| 148 | .custom_tag( | ||
| 149 | SingleLetterTag::lowercase(Alphabet::D), | ||
| 150 | identifier.to_string(), | ||
| 151 | ); | ||
| 152 | |||
| 153 | match database.query(filter).await { | ||
| 154 | Ok(events) => { | ||
| 155 | let mut authorized = Vec::new(); | ||
| 156 | let state_author_hex = state_author.to_hex(); | ||
| 157 | |||
| 158 | for event in events { | ||
| 159 | if let Ok(announcement) = RepositoryAnnouncement::from_event(event.clone()) { | ||
| 160 | // Check if state author is authorized for this announcement | ||
| 161 | let is_owner = event.pubkey == *state_author; | ||
| 162 | let is_maintainer = announcement.maintainers.contains(&state_author_hex); | ||
| 163 | |||
| 164 | if is_owner || is_maintainer { | ||
| 165 | tracing::debug!( | ||
| 166 | "Found authorized announcement for {}: owner={}, maintainer={}", | ||
| 167 | identifier, | ||
| 168 | if is_owner { event.pubkey.to_hex() } else { "n/a".to_string() }, | ||
| 169 | is_maintainer | ||
| 170 | ); | ||
| 171 | authorized.push(announcement); | ||
| 172 | } | ||
| 173 | } | ||
| 174 | } | ||
| 175 | Ok(authorized) | ||
| 176 | } | ||
| 177 | Err(e) => Err(format!("Database query failed: {}", e)), | ||
| 178 | } | ||
| 179 | } | ||
| 180 | |||
| 181 | /// Try to set repository HEAD for all authorized announcement owners | ||
| 182 | /// | ||
| 183 | /// Per GRASP-01: "MUST set repository HEAD per repository state announcement | ||
| 184 | /// as soon as the git data related to that branch has been received." | ||
| 185 | /// | ||
| 186 | /// This function: | ||
| 187 | /// 1. Checks if this state event is the latest for the identifier | ||
| 188 | /// 2. Finds all announcements where the state author is authorized | ||
| 189 | /// 3. Updates HEAD in each relevant repository | ||
| 190 | /// | ||
| 191 | /// Returns Ok(count) with the number of repositories updated. | ||
| 192 | async fn try_set_head_for_authorized_repos( | ||
| 193 | &self, | ||
| 194 | database: &Arc<MemoryDatabase>, | ||
| 195 | state: &RepositoryState, | ||
| 196 | ) -> Result<usize, String> { | ||
| 197 | // Check if state has a HEAD reference | ||
| 198 | let head_ref = match &state.head { | ||
| 199 | Some(h) => h, | ||
| 200 | None => { | ||
| 201 | tracing::debug!( | ||
| 202 | "State event for {} has no HEAD reference", | ||
| 203 | state.identifier | ||
| 204 | ); | ||
| 205 | return Ok(0); | ||
| 206 | } | ||
| 207 | }; | ||
| 208 | |||
| 209 | // Get the branch name and commit | ||
| 210 | let branch_name = match state.get_head_branch() { | ||
| 211 | Some(b) => b, | ||
| 212 | None => { | ||
| 213 | tracing::debug!( | ||
| 214 | "State event for {} has invalid HEAD format: {}", | ||
| 215 | state.identifier, | ||
| 216 | head_ref | ||
| 217 | ); | ||
| 218 | return Ok(0); | ||
| 219 | } | ||
| 220 | }; | ||
| 221 | |||
| 222 | let head_commit = match state.get_branch_commit(branch_name) { | ||
| 223 | Some(c) => c, | ||
| 224 | None => { | ||
| 225 | tracing::debug!( | ||
| 226 | "State event for {} HEAD branch {} has no commit in state", | ||
| 227 | state.identifier, | ||
| 228 | branch_name | ||
| 229 | ); | ||
| 230 | return Ok(0); | ||
| 231 | } | ||
| 232 | }; | ||
| 233 | |||
| 234 | // Find all announcements where state author is authorized | ||
| 235 | let announcements = Self::find_authorized_announcements( | ||
| 236 | database, | ||
| 237 | &state.identifier, | ||
| 238 | &state.event.pubkey, | ||
| 239 | ).await?; | ||
| 240 | |||
| 241 | if announcements.is_empty() { | ||
| 242 | tracing::debug!( | ||
| 243 | "No authorized announcements found for state {} by {}", | ||
| 244 | state.identifier, | ||
| 245 | state.event.pubkey.to_hex() | ||
| 246 | ); | ||
| 247 | return Ok(0); | ||
| 248 | } | ||
| 249 | |||
| 250 | // Update HEAD in each authorized announcement's repository | ||
| 251 | let mut updated_count = 0; | ||
| 252 | for announcement in &announcements { | ||
| 253 | // Build the list of authorized pubkeys for this specific announcement | ||
| 254 | // (owner + maintainers) | ||
| 255 | let mut authorized_pubkeys = vec![announcement.event.pubkey]; | ||
| 256 | for maintainer_hex in &announcement.maintainers { | ||
| 257 | if let Ok(pk) = PublicKey::from_hex(maintainer_hex) { | ||
| 258 | authorized_pubkeys.push(pk); | ||
| 259 | } | ||
| 260 | } | ||
| 261 | |||
| 262 | // Check if this is the latest state event for THIS announcement's context | ||
| 263 | // Different owners with the same identifier should not interfere | ||
| 264 | if !Self::is_latest_state_for_identifier(database, state, &authorized_pubkeys).await? { | ||
| 265 | tracing::debug!( | ||
| 266 | "Skipping HEAD update for {} in {}'s repo - not the latest state event for this context", | ||
| 267 | state.identifier, | ||
| 268 | announcement.event.pubkey.to_hex() | ||
| 269 | ); | ||
| 270 | continue; | ||
| 271 | } | ||
| 272 | |||
| 273 | // Build repository path: <git_data_path>/<owner_npub>/<identifier>.git | ||
| 274 | let repo_path = self.git_data_path.join(&announcement.repo_path()); | ||
| 275 | |||
| 276 | match git::try_set_head_if_available(&repo_path, head_ref, head_commit) { | ||
| 277 | Ok(true) => { | ||
| 278 | tracing::info!( | ||
| 279 | "Set HEAD to {} in repository {} (from state by {})", | ||
| 280 | head_ref, | ||
| 281 | repo_path.display(), | ||
| 282 | state.event.pubkey.to_hex() | ||
| 283 | ); | ||
| 284 | updated_count += 1; | ||
| 285 | } | ||
| 286 | Ok(false) => { | ||
| 287 | tracing::debug!( | ||
| 288 | "HEAD commit {} not available yet in {}", | ||
| 289 | head_commit, | ||
| 290 | repo_path.display() | ||
| 291 | ); | ||
| 292 | } | ||
| 293 | Err(e) => { | ||
| 294 | tracing::warn!( | ||
| 295 | "Failed to set HEAD in {}: {}", | ||
| 296 | repo_path.display(), | ||
| 297 | e | ||
| 298 | ); | ||
| 299 | } | ||
| 300 | } | ||
| 301 | } | ||
| 302 | |||
| 303 | Ok(updated_count) | ||
| 304 | } | ||
| 305 | |||
| 80 | /// Extract all reference tags from an event (a, A, q, e, E) | 306 | /// Extract all reference tags from an event (a, A, q, e, E) |
| 81 | /// Returns (addressable_refs, event_refs) | 307 | /// Returns (addressable_refs, event_refs) |
| 82 | fn extract_reference_tags(event: &Event) -> (Vec<String>, Vec<EventId>) { | 308 | fn extract_reference_tags(event: &Event) -> (Vec<String>, Vec<EventId>) { |
| @@ -345,13 +571,53 @@ impl WritePolicy for Nip34WritePolicy { | |||
| 345 | PolicyResult::Reject(e.to_string()) | 571 | PolicyResult::Reject(e.to_string()) |
| 346 | } | 572 | } |
| 347 | }, | 573 | }, |
| 348 | KIND_REPOSITORY_STATE =>match validate_state(event) { | 574 | KIND_REPOSITORY_STATE => match validate_state(event) { |
| 349 | Ok(_) => { | 575 | Ok(_) => { |
| 350 | tracing::debug!( | 576 | // Parse state to get HEAD and branch info |
| 351 | "Accepted repository state: {}", | 577 | match RepositoryState::from_event(event.clone()) { |
| 352 | event_id_str | 578 | Ok(state) => { |
| 353 | ); | 579 | // Try to set HEAD for all authorized repos if this is the latest state |
| 354 | PolicyResult::Accept | 580 | match self.try_set_head_for_authorized_repos(&database, &state).await { |
| 581 | Ok(count) if count > 0 => { | ||
| 582 | tracing::info!( | ||
| 583 | "Set HEAD from state event {} for {} repo(s) with identifier {}", | ||
| 584 | event_id_str, | ||
| 585 | count, | ||
| 586 | state.identifier | ||
| 587 | ); | ||
| 588 | } | ||
| 589 | Ok(_) => { | ||
| 590 | tracing::debug!( | ||
| 591 | "HEAD not set from state {} - git data not available yet or not latest", | ||
| 592 | event_id_str | ||
| 593 | ); | ||
| 594 | } | ||
| 595 | Err(e) => { | ||
| 596 | tracing::warn!( | ||
| 597 | "Failed to process HEAD from state {}: {}", | ||
| 598 | event_id_str, | ||
| 599 | e | ||
| 600 | ); | ||
| 601 | } | ||
| 602 | } | ||
| 603 | |||
| 604 | tracing::debug!( | ||
| 605 | "Accepted repository state: {}", | ||
| 606 | event_id_str | ||
| 607 | ); | ||
| 608 | PolicyResult::Accept | ||
| 609 | } | ||
| 610 | Err(e) => { | ||
| 611 | tracing::warn!( | ||
| 612 | "Failed to parse repository state {}: {}", | ||
| 613 | event_id_str, | ||
| 614 | e | ||
| 615 | ); | ||
| 616 | // Still accept the event even if we can't parse it | ||
| 617 | // The validation passed, so it's structurally valid | ||
| 618 | PolicyResult::Accept | ||
| 619 | } | ||
| 620 | } | ||
| 355 | } | 621 | } |
| 356 | Err(e) => { | 622 | Err(e) => { |
| 357 | tracing::warn!( | 623 | tracing::warn!( |
diff --git a/src/nostr/events.rs b/src/nostr/events.rs index 643269a..97688b1 100644 --- a/src/nostr/events.rs +++ b/src/nostr/events.rs | |||
| @@ -167,6 +167,8 @@ pub struct RepositoryState { | |||
| 167 | pub identifier: String, | 167 | pub identifier: String, |
| 168 | pub branches: Vec<BranchState>, | 168 | pub branches: Vec<BranchState>, |
| 169 | pub tags: Vec<TagState>, | 169 | pub tags: Vec<TagState>, |
| 170 | /// HEAD reference (e.g., "refs/heads/main") if specified | ||
| 171 | pub head: Option<String>, | ||
| 170 | } | 172 | } |
| 171 | 173 | ||
| 172 | /// Branch state (ref with commit hash) | 174 | /// Branch state (ref with commit hash) |
| @@ -255,11 +257,39 @@ impl RepositoryState { | |||
| 255 | }) | 257 | }) |
| 256 | .collect(); | 258 | .collect(); |
| 257 | 259 | ||
| 260 | // Extract HEAD reference per NIP-34 | ||
| 261 | // Tag format: ["HEAD", "ref: refs/heads/main"] or ["HEAD", "refs/heads/main"] | ||
| 262 | let head = event | ||
| 263 | .tags | ||
| 264 | .iter() | ||
| 265 | .find(|t| { | ||
| 266 | if let TagKind::Custom(s) = t.kind() { | ||
| 267 | s.as_ref() == "HEAD" | ||
| 268 | } else { | ||
| 269 | false | ||
| 270 | } | ||
| 271 | }) | ||
| 272 | .and_then(|t| { | ||
| 273 | let parts = t.clone().to_vec(); | ||
| 274 | if parts.len() >= 2 { | ||
| 275 | let head_value = &parts[1]; | ||
| 276 | // Handle both "ref: refs/heads/main" and "refs/heads/main" formats | ||
| 277 | if let Some(stripped) = head_value.strip_prefix("ref: ") { | ||
| 278 | Some(stripped.to_string()) | ||
| 279 | } else { | ||
| 280 | Some(head_value.clone()) | ||
| 281 | } | ||
| 282 | } else { | ||
| 283 | None | ||
| 284 | } | ||
| 285 | }); | ||
| 286 | |||
| 258 | Ok(RepositoryState { | 287 | Ok(RepositoryState { |
| 259 | event, | 288 | event, |
| 260 | identifier, | 289 | identifier, |
| 261 | branches, | 290 | branches, |
| 262 | tags, | 291 | tags, |
| 292 | head, | ||
| 263 | }) | 293 | }) |
| 264 | } | 294 | } |
| 265 | 295 | ||
| @@ -283,6 +313,23 @@ impl RepositoryState { | |||
| 283 | pub fn owner_npub(&self) -> String { | 313 | pub fn owner_npub(&self) -> String { |
| 284 | self.event.pubkey.to_bech32().unwrap_or_default() | 314 | self.event.pubkey.to_bech32().unwrap_or_default() |
| 285 | } | 315 | } |
| 316 | |||
| 317 | /// Get the HEAD branch name (without refs/heads/ prefix) | ||
| 318 | pub fn get_head_branch(&self) -> Option<&str> { | ||
| 319 | self.head.as_ref().and_then(|h| { | ||
| 320 | h.strip_prefix("refs/heads/") | ||
| 321 | }) | ||
| 322 | } | ||
| 323 | |||
| 324 | /// Check if the HEAD commit is available in the git repository | ||
| 325 | /// Returns true if we have the git data for the HEAD branch | ||
| 326 | pub fn head_commit_available(&self) -> bool { | ||
| 327 | if let Some(head_branch) = self.get_head_branch() { | ||
| 328 | self.get_branch_commit(head_branch).is_some() | ||
| 329 | } else { | ||
| 330 | false | ||
| 331 | } | ||
| 332 | } | ||
| 286 | } | 333 | } |
| 287 | 334 | ||
| 288 | /// Validate a repository announcement according to GRASP-01 | 335 | /// Validate a repository announcement according to GRASP-01 |
| @@ -601,4 +648,131 @@ mod tests { | |||
| 601 | assert_eq!(state.get_branch_commit("main"), Some("a1b2c3d4")); | 648 | assert_eq!(state.get_branch_commit("main"), Some("a1b2c3d4")); |
| 602 | assert_eq!(state.get_tag_commit("v1.0.0"), Some("e5f6g7h8")); | 649 | assert_eq!(state.get_tag_commit("v1.0.0"), Some("e5f6g7h8")); |
| 603 | } | 650 | } |
| 651 | |||
| 652 | #[test] | ||
| 653 | fn test_state_with_head_ref_prefix() { | ||
| 654 | use nostr_sdk::Tag; | ||
| 655 | |||
| 656 | let keys = create_test_keys(); | ||
| 657 | let mut tags = vec![Tag::custom( | ||
| 658 | nostr_sdk::TagKind::d(), | ||
| 659 | vec!["test-repo".to_string()], | ||
| 660 | )]; | ||
| 661 | |||
| 662 | // Add branch | ||
| 663 | tags.push(Tag::custom( | ||
| 664 | nostr_sdk::TagKind::Custom("refs/heads/main".into()), | ||
| 665 | vec!["a1b2c3d4e5f6g7h8".to_string()], | ||
| 666 | )); | ||
| 667 | |||
| 668 | // Add HEAD with "ref: " prefix (common NIP-34 format) | ||
| 669 | tags.push(Tag::custom( | ||
| 670 | nostr_sdk::TagKind::Custom("HEAD".into()), | ||
| 671 | vec!["ref: refs/heads/main".to_string()], | ||
| 672 | )); | ||
| 673 | |||
| 674 | let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") | ||
| 675 | .tags(tags) | ||
| 676 | .sign_with_keys(&keys) | ||
| 677 | .unwrap(); | ||
| 678 | |||
| 679 | let state = RepositoryState::from_event(event).unwrap(); | ||
| 680 | assert_eq!(state.head, Some("refs/heads/main".to_string())); | ||
| 681 | assert_eq!(state.get_head_branch(), Some("main")); | ||
| 682 | assert!(state.head_commit_available()); | ||
| 683 | } | ||
| 684 | |||
| 685 | #[test] | ||
| 686 | fn test_state_with_head_no_prefix() { | ||
| 687 | use nostr_sdk::Tag; | ||
| 688 | |||
| 689 | let keys = create_test_keys(); | ||
| 690 | let mut tags = vec![Tag::custom( | ||
| 691 | nostr_sdk::TagKind::d(), | ||
| 692 | vec!["test-repo".to_string()], | ||
| 693 | )]; | ||
| 694 | |||
| 695 | // Add branch | ||
| 696 | tags.push(Tag::custom( | ||
| 697 | nostr_sdk::TagKind::Custom("refs/heads/develop".into()), | ||
| 698 | vec!["deadbeefcafe".to_string()], | ||
| 699 | )); | ||
| 700 | |||
| 701 | // Add HEAD without "ref: " prefix (also valid) | ||
| 702 | tags.push(Tag::custom( | ||
| 703 | nostr_sdk::TagKind::Custom("HEAD".into()), | ||
| 704 | vec!["refs/heads/develop".to_string()], | ||
| 705 | )); | ||
| 706 | |||
| 707 | let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") | ||
| 708 | .tags(tags) | ||
| 709 | .sign_with_keys(&keys) | ||
| 710 | .unwrap(); | ||
| 711 | |||
| 712 | let state = RepositoryState::from_event(event).unwrap(); | ||
| 713 | assert_eq!(state.head, Some("refs/heads/develop".to_string())); | ||
| 714 | assert_eq!(state.get_head_branch(), Some("develop")); | ||
| 715 | assert!(state.head_commit_available()); | ||
| 716 | } | ||
| 717 | |||
| 718 | #[test] | ||
| 719 | fn test_state_without_head() { | ||
| 720 | use nostr_sdk::Tag; | ||
| 721 | |||
| 722 | let keys = create_test_keys(); | ||
| 723 | let tags = vec![ | ||
| 724 | Tag::custom( | ||
| 725 | nostr_sdk::TagKind::d(), | ||
| 726 | vec!["test-repo".to_string()], | ||
| 727 | ), | ||
| 728 | Tag::custom( | ||
| 729 | nostr_sdk::TagKind::Custom("refs/heads/main".into()), | ||
| 730 | vec!["a1b2c3d4".to_string()], | ||
| 731 | ), | ||
| 732 | ]; | ||
| 733 | |||
| 734 | let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") | ||
| 735 | .tags(tags) | ||
| 736 | .sign_with_keys(&keys) | ||
| 737 | .unwrap(); | ||
| 738 | |||
| 739 | let state = RepositoryState::from_event(event).unwrap(); | ||
| 740 | assert_eq!(state.head, None); | ||
| 741 | assert_eq!(state.get_head_branch(), None); | ||
| 742 | assert!(!state.head_commit_available()); | ||
| 743 | } | ||
| 744 | |||
| 745 | #[test] | ||
| 746 | fn test_state_head_commit_not_available() { | ||
| 747 | use nostr_sdk::Tag; | ||
| 748 | |||
| 749 | let keys = create_test_keys(); | ||
| 750 | let mut tags = vec![Tag::custom( | ||
| 751 | nostr_sdk::TagKind::d(), | ||
| 752 | vec!["test-repo".to_string()], | ||
| 753 | )]; | ||
| 754 | |||
| 755 | // Add branch for "main" | ||
| 756 | tags.push(Tag::custom( | ||
| 757 | nostr_sdk::TagKind::Custom("refs/heads/main".into()), | ||
| 758 | vec!["a1b2c3d4".to_string()], | ||
| 759 | )); | ||
| 760 | |||
| 761 | // HEAD points to "develop" which doesn't exist in branches | ||
| 762 | tags.push(Tag::custom( | ||
| 763 | nostr_sdk::TagKind::Custom("HEAD".into()), | ||
| 764 | vec!["refs/heads/develop".to_string()], | ||
| 765 | )); | ||
| 766 | |||
| 767 | let event = EventBuilder::new(Kind::from(KIND_REPOSITORY_STATE), "") | ||
| 768 | .tags(tags) | ||
| 769 | .sign_with_keys(&keys) | ||
| 770 | .unwrap(); | ||
| 771 | |||
| 772 | let state = RepositoryState::from_event(event).unwrap(); | ||
| 773 | assert_eq!(state.head, Some("refs/heads/develop".to_string())); | ||
| 774 | assert_eq!(state.get_head_branch(), Some("develop")); | ||
| 775 | // HEAD points to develop but only main branch exists in state | ||
| 776 | assert!(!state.head_commit_available()); | ||
| 777 | } | ||
| 604 | } | 778 | } |