1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
|
//! Helper functions for purgatory state event processing.
//!
//! These functions handle the late-binding extraction and matching of git refs
//! from state events. Refs are extracted at git push time rather than event
//! arrival time to enable flexible matching logic.
use super::{RefPair, RefUpdate};
use nostr_sdk::prelude::*;
use std::collections::HashMap;
/// Extract ref pairs from a state event (kind 30618).
///
/// Parses all `refs/heads/*` and `refs/tags/*` tags from the event,
/// creating RefPair instances with the full ref name and target object SHA.
///
/// # Arguments
/// * `event` - The state event to extract refs from
///
/// # Returns
/// Vector of RefPair instances, one for each ref tag found
///
/// # Tag Format
/// State events use custom tags where the tag kind is the ref name:
/// - Tag kind: "refs/heads/main" or "refs/tags/v1.0"
/// - First value: commit SHA or annotated tag SHA
///
/// # Example
/// ```ignore
/// // Event with tags:
/// // ["refs/heads/main", "abc123..."]
/// // ["refs/tags/v1.0", "def456..."]
/// let refs = extract_refs_from_state(&event);
/// // Returns: [
/// // RefPair { ref_name: "refs/heads/main", object_sha: "abc123..." },
/// // RefPair { ref_name: "refs/tags/v1.0", object_sha: "def456..." }
/// // ]
/// ```
pub fn extract_refs_from_state(event: &Event) -> Vec<RefPair> {
event
.tags
.iter()
.filter_map(|tag| {
// Check if this is a custom tag with a ref name
if let TagKind::Custom(ref_name) = tag.kind() {
let ref_str = ref_name.as_ref();
// Only process refs/heads/* and refs/tags/*
if ref_str.starts_with("refs/heads/") || ref_str.starts_with("refs/tags/") {
// Get the object SHA (first value in tag)
let parts = tag.clone().to_vec();
if parts.len() >= 2 {
return Some(RefPair {
ref_name: ref_str.to_string(),
object_sha: parts[1].clone(),
});
}
}
}
None
})
.collect()
}
/// Check if a state event can be satisfied by ref updates plus local refs.
///
/// Returns true if applying the ref updates to local state results in exactly
/// the state declared in the event. This means:
/// 1. Filter local_refs to only branches (refs/heads/*) and tags (refs/tags/*)
/// 2. Apply pushed_updates to create a "would-be" state
/// 3. Compare would-be state with event's declared state - must match exactly
///
/// This implements correct authorization: the push must transform local state
/// into the declared state, accounting for additions, deletions, and modifications.
///
/// # Arguments
/// * `event` - The state event to check
/// * `pushed_updates` - Ref updates in the current push operation
/// * `local_refs` - Refs already existing locally (ref_name -> SHA)
///
/// # Returns
/// true if push transforms local state into declared state, false otherwise
///
/// # Example
/// ```ignore
/// // State event declares: refs/heads/main@abc123
/// // Local: refs/heads/main@old123, refs/heads/dev@def456
/// // Push updates: main old123->abc123, dev def456->0000 (delete)
/// // Result: false (event doesn't declare dev deletion)
/// ```
pub fn can_satisfy_state(
event: &Event,
pushed_updates: &[RefUpdate],
local_refs: &HashMap<String, String>,
) -> bool {
let state_refs = extract_refs_from_state(event);
// Filter local_refs to only branches and tags
let mut would_be_state: HashMap<String, String> = local_refs
.iter()
.filter(|(ref_name, _)| {
ref_name.starts_with("refs/heads/") || ref_name.starts_with("refs/tags/")
})
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
// Apply all pushed updates to create the would-be state
for update in pushed_updates {
// Only process branches and tags
if !update.ref_name.starts_with("refs/heads/") && !update.ref_name.starts_with("refs/tags/")
{
continue;
}
if update.is_deletion() {
// Remove from would-be state
would_be_state.remove(&update.ref_name);
} else {
// Create or modify in would-be state
would_be_state.insert(update.ref_name.clone(), update.new_oid.clone());
}
}
// Convert event's state refs to a HashMap for comparison
let declared_state: HashMap<String, String> = state_refs
.into_iter()
.map(|r| (r.ref_name, r.object_sha))
.collect();
// would_be_state must exactly match declared_state
would_be_state == declared_state
}
/// Get refs from state event that aren't in pushed_refs.
///
/// Returns refs that need to be present but aren't being pushed.
/// These refs should exist in local_refs for the state to be satisfiable.
/// Useful for error messages showing what's missing.
///
/// # Arguments
/// * `event` - The state event to check
/// * `pushed_refs` - Refs being pushed in the current operation
///
/// # Returns
/// Vector of RefPair instances for refs not in pushed_refs
///
/// # Example
/// ```ignore
/// // State event declares: refs/heads/main@abc123, refs/heads/dev@def456
/// // Pushed: refs/heads/main@abc123
/// // Result: [RefPair { ref_name: "refs/heads/dev", object_sha: "def456" }]
/// ```
pub fn get_unpushed_refs(event: &Event, pushed_refs: &[RefPair]) -> Vec<RefPair> {
let state_refs = extract_refs_from_state(event);
state_refs
.into_iter()
.filter(|state_ref| {
// Include if NOT in pushed_refs (by name and SHA)
!pushed_refs.iter().any(|pushed_ref| {
pushed_ref.ref_name == state_ref.ref_name
&& pushed_ref.object_sha == state_ref.object_sha
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use nostr_sdk::{EventBuilder, Keys, Tag};
fn create_test_state_event(identifier: &str, refs: Vec<(&str, &str)>) -> Event {
let keys = Keys::generate();
let mut tags = vec![Tag::custom(TagKind::d(), vec![identifier.to_string()])];
for (ref_name, sha) in refs {
tags.push(Tag::custom(
TagKind::custom(ref_name),
vec![sha.to_string()],
));
}
EventBuilder::new(Kind::from(30618), "")
.tags(tags)
.sign_with_keys(&keys)
.unwrap()
}
#[test]
fn test_extract_refs_from_state() {
let event = create_test_state_event(
"test-repo",
vec![
("refs/heads/main", "abc123"),
("refs/heads/dev", "def456"),
("refs/tags/v1.0", "789xyz"),
],
);
let refs = extract_refs_from_state(&event);
assert_eq!(refs.len(), 3);
assert!(refs
.iter()
.any(|r| r.ref_name == "refs/heads/main" && r.object_sha == "abc123"));
assert!(refs
.iter()
.any(|r| r.ref_name == "refs/heads/dev" && r.object_sha == "def456"));
assert!(refs
.iter()
.any(|r| r.ref_name == "refs/tags/v1.0" && r.object_sha == "789xyz"));
}
#[test]
fn test_extract_refs_ignores_non_ref_tags() {
let keys = Keys::generate();
let tags = vec![
Tag::custom(TagKind::d(), vec!["test-repo".to_string()]),
Tag::custom(
TagKind::custom("refs/heads/main"),
vec!["abc123".to_string()],
),
Tag::custom(TagKind::custom("some-other-tag"), vec!["value".to_string()]),
];
let event = EventBuilder::new(Kind::from(30618), "")
.tags(tags)
.sign_with_keys(&keys)
.unwrap();
let refs = extract_refs_from_state(&event);
// Should only extract the refs/heads/main tag
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].ref_name, "refs/heads/main");
}
#[test]
fn test_can_satisfy_state_all_in_pushed() {
let event = create_test_state_event(
"test-repo",
vec![("refs/heads/main", "abc123"), ("refs/heads/dev", "def456")],
);
let pushed_updates = vec![
RefUpdate {
old_oid: "0000000000000000000000000000000000000000".to_string(),
new_oid: "abc123".to_string(),
ref_name: "refs/heads/main".to_string(),
},
RefUpdate {
old_oid: "0000000000000000000000000000000000000000".to_string(),
new_oid: "def456".to_string(),
ref_name: "refs/heads/dev".to_string(),
},
];
let local_refs = HashMap::new();
assert!(can_satisfy_state(&event, &pushed_updates, &local_refs));
}
#[test]
fn test_can_satisfy_state_split_between_pushed_and_local() {
let event = create_test_state_event(
"test-repo",
vec![("refs/heads/main", "abc123"), ("refs/heads/dev", "def456")],
);
let pushed_updates = vec![RefUpdate {
old_oid: "0000000000000000000000000000000000000000".to_string(),
new_oid: "abc123".to_string(),
ref_name: "refs/heads/main".to_string(),
}];
let mut local_refs = HashMap::new();
local_refs.insert("refs/heads/dev".to_string(), "def456".to_string());
assert!(can_satisfy_state(&event, &pushed_updates, &local_refs));
}
#[test]
fn test_can_satisfy_state_missing_ref() {
let event = create_test_state_event(
"test-repo",
vec![("refs/heads/main", "abc123"), ("refs/heads/dev", "def456")],
);
let pushed_updates = vec![RefUpdate {
old_oid: "0000000000000000000000000000000000000000".to_string(),
new_oid: "abc123".to_string(),
ref_name: "refs/heads/main".to_string(),
}];
let local_refs = HashMap::new();
// dev ref is missing
assert!(!can_satisfy_state(&event, &pushed_updates, &local_refs));
}
#[test]
fn test_can_satisfy_state_modification() {
let event = create_test_state_event(
"test-repo",
vec![("refs/heads/main", "abc123"), ("refs/heads/dev", "def456")],
);
let pushed_updates = vec![
RefUpdate {
old_oid: "old123".to_string(),
new_oid: "abc123".to_string(),
ref_name: "refs/heads/main".to_string(),
},
RefUpdate {
old_oid: "wrong-sha".to_string(),
new_oid: "def456".to_string(),
ref_name: "refs/heads/dev".to_string(),
},
];
let mut local_refs = HashMap::new();
local_refs.insert("refs/heads/main".to_string(), "old123".to_string());
local_refs.insert("refs/heads/dev".to_string(), "wrong-sha".to_string());
// Should succeed because push updates both to match event
assert!(can_satisfy_state(&event, &pushed_updates, &local_refs));
}
#[test]
fn test_can_satisfy_state_rejects_extra_refs() {
let event = create_test_state_event("test-repo", vec![("refs/heads/main", "abc123")]);
let pushed_updates = vec![
RefUpdate {
old_oid: "0000000000000000000000000000000000000000".to_string(),
new_oid: "abc123".to_string(),
ref_name: "refs/heads/main".to_string(),
},
RefUpdate {
old_oid: "old456".to_string(),
new_oid: "def456".to_string(),
ref_name: "refs/heads/dev".to_string(),
},
];
let mut local_refs = HashMap::new();
local_refs.insert("refs/heads/dev".to_string(), "old456".to_string());
// Should fail because event doesn't declare dev
assert!(!can_satisfy_state(&event, &pushed_updates, &local_refs));
}
#[test]
fn test_can_satisfy_state_filters_non_branch_tag_refs() {
let event = create_test_state_event("test-repo", vec![("refs/heads/main", "abc123")]);
let pushed_updates = vec![RefUpdate {
old_oid: "0000000000000000000000000000000000000000".to_string(),
new_oid: "abc123".to_string(),
ref_name: "refs/heads/main".to_string(),
}];
let mut local_refs = HashMap::new();
// Add some non-branch/non-tag refs that should be filtered out
local_refs.insert("refs/pull/123/head".to_string(), "xyz789".to_string());
local_refs.insert("refs/some/other/thing".to_string(), "aaa111".to_string());
// Should succeed - non-branch/tag refs are filtered out
assert!(can_satisfy_state(&event, &pushed_updates, &local_refs));
}
#[test]
fn test_can_satisfy_state_empty_event() {
let event = create_test_state_event("test-repo", vec![]);
let pushed_refs = vec![];
let local_refs = HashMap::new();
// Empty state event is satisfied
assert!(can_satisfy_state(&event, &pushed_refs, &local_refs));
}
#[test]
fn test_get_unpushed_refs() {
let event = create_test_state_event(
"test-repo",
vec![
("refs/heads/main", "abc123"),
("refs/heads/dev", "def456"),
("refs/tags/v1.0", "789xyz"),
],
);
let pushed_refs = vec![RefPair {
ref_name: "refs/heads/main".to_string(),
object_sha: "abc123".to_string(),
}];
let unpushed = get_unpushed_refs(&event, &pushed_refs);
assert_eq!(unpushed.len(), 2);
assert!(unpushed.iter().any(|r| r.ref_name == "refs/heads/dev"));
assert!(unpushed.iter().any(|r| r.ref_name == "refs/tags/v1.0"));
}
#[test]
fn test_get_unpushed_refs_all_pushed() {
let event = create_test_state_event("test-repo", vec![("refs/heads/main", "abc123")]);
let pushed_refs = vec![RefPair {
ref_name: "refs/heads/main".to_string(),
object_sha: "abc123".to_string(),
}];
let unpushed = get_unpushed_refs(&event, &pushed_refs);
assert_eq!(unpushed.len(), 0);
}
#[test]
fn test_get_unpushed_refs_sha_mismatch() {
let event = create_test_state_event("test-repo", vec![("refs/heads/main", "abc123")]);
let pushed_refs = vec![RefPair {
ref_name: "refs/heads/main".to_string(),
object_sha: "different-sha".to_string(), // Different SHA
}];
let unpushed = get_unpushed_refs(&event, &pushed_refs);
// Should still be unpushed because SHA doesn't match
assert_eq!(unpushed.len(), 1);
assert_eq!(unpushed[0].ref_name, "refs/heads/main");
assert_eq!(unpushed[0].object_sha, "abc123");
}
}
|