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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
|
# GRASP Audit Tool - Patterns and Learnings
**Purpose:** Document grasp-audit architecture, patterns, and lessons learned
**Last Updated:** November 4, 2025
---
## Overview
`grasp-audit` is a compliance testing tool for GRASP (Git Relays Authorized via Signed-Nostr Proofs) protocol implementations. It tests both Nostr relay compliance (NIP-01) and GRASP-specific functionality.
---
## Architecture Decisions
### Separate Crate Strategy
**Decision:** Build `grasp-audit` as a separate crate from `ngit-grasp`
**Why:**
1. **Parallel Development**: Can build tests before implementation
2. **Isolated Testing**: Tests run in isolation (CI/CD safe)
3. **Production Auditing**: Can audit live production services
4. **Reusability**: Other GRASP implementations can use it
**Location:** `grasp-audit/` subdirectory with own `Cargo.toml` and `flake.nix`
---
### Audit Event Tagging Strategy
**Problem:** Test events pollute the relay and need cleanup without deletion events.
**Solution:** Use special tags to mark audit events:
```rust
// Every audit event includes these tags
[
["t", "grasp-audit-test-event"], // Marker
["t", "audit-{run-id}"], // Run isolation
["t", "audit-cleanup-after-{timestamp}"] // Cleanup time
]
```
**Benefits:**
- ✅ **Queryable**: Can find all audit events via tag filter
- ✅ **Isolated**: Each test run has unique run ID
- ✅ **Self-cleaning**: Cleanup timestamp indicates when to delete
- ✅ **No deletion events**: Direct database cleanup, no KIND 5 events
- ✅ **Production safe**: Won't interfere with real events
**Reference:** See `docs/archive/2025-11-04-tag-migration.md`
---
### Standard "t" Tags vs Custom Tags
**Evolution:**
1. **Original**: Custom single-letter tags (`g`, `r`, `c`)
2. **Current**: Standard NIP-01 "t" tags with prefixed values
**Why we changed:**
- ❌ Custom tags could conflict with other systems
- ✅ "t" tag is standard for categorization/topics
- ✅ Multiple "t" tags are expected and supported
- ✅ Self-documenting values (`audit-{run-id}` vs just `{run-id}`)
- ✅ Better namespacing with prefixes
**Migration:** Completed November 4, 2025
---
## Code Patterns
### Audit Configuration
```rust
use grasp_audit::audit::AuditConfig;
// CI mode - isolated test runs
let config = AuditConfig::ci();
// Generates UUID run ID: "ci-{uuid}"
// Cleanup after 1 hour
// Production mode - persistent run ID
let config = AuditConfig::production("prod-server-1");
// Uses provided run ID
// Cleanup after 24 hours
```
**When to use:**
- **CI mode**: Automated testing, parallel runs, temporary
- **Production mode**: Manual audits, monitoring, persistent
---
### Creating Audit Events
```rust
use grasp_audit::audit::{AuditConfig, AuditEventBuilder};
use nostr_sdk::prelude::*;
let config = AuditConfig::ci();
let keys = Keys::generate();
// Create audit event
let event = AuditEventBuilder::new(&config, Kind::TextNote, "test content")
.build(&keys)?;
// Event automatically includes:
// - Audit marker tag
// - Run ID tag
// - Cleanup timestamp tag
```
---
### Querying Audit Events
```rust
use grasp_audit::client::AuditClient;
use grasp_audit::audit::AuditConfig;
let config = AuditConfig::ci();
let client = AuditClient::new(config, keys);
// Connect to relay
client.add_relay("ws://localhost:7000").await?;
client.connect().await;
// Query audit events for this run
let events = client.query().await?;
// Events are filtered by:
// - "grasp-audit-test-event" marker
// - Current run ID
```
---
### Test Isolation
**Each test run is isolated by unique run ID:**
```rust
// CI mode generates unique UUID per run
let config1 = AuditConfig::ci();
let config2 = AuditConfig::ci();
// config1.run_id != config2.run_id
// Tests won't interfere with each other
```
**Benefits:**
- ✅ Parallel CI/CD runs don't conflict
- ✅ Can run multiple test suites simultaneously
- ✅ Easy to identify which run created which events
- ✅ Cleanup can target specific runs
---
### Cleanup Strategy
**Two-phase cleanup:**
1. **Automatic expiry** via cleanup timestamp tag
2. **Manual cleanup** by querying and deleting
```rust
// Events include cleanup timestamp
["t", "audit-cleanup-after-1730707200"]
// Cleanup process:
// 1. Query events with expired cleanup timestamp
// 2. Delete from database directly (no KIND 5)
// 3. Avoid deletion event pollution
```
**Implementation:** To be built in relay (not in audit tool)
---
## Testing Strategy
### Test Organization
```
grasp-audit/src/specs/
├── nip01_smoke.rs # NIP-01 basic functionality
├── grasp_01_relay.rs # GRASP-01 relay requirements (planned)
└── mod.rs # Test suite registry
```
### Unit vs Integration Tests
**Unit Tests** (no relay required):
```rust
#[cfg(test)]
mod tests {
#[test]
fn test_audit_config() {
let config = AuditConfig::ci();
assert!(config.run_id.starts_with("ci-"));
}
}
```
**Integration Tests** (relay required):
```rust
#[cfg(test)]
mod tests {
#[tokio::test]
#[ignore] // Requires relay
async fn test_smoke_tests_against_relay() {
// Test against real relay
}
}
```
**Running tests:**
```bash
# Unit tests (fast, no dependencies)
cargo test --lib
# Integration tests (requires relay)
docker run --rm -p 7000:7000 scsibug/nostr-rs-relay
cargo test -- --ignored
```
---
### Test Result Reporting
```rust
use grasp_audit::result::AuditResult;
// Run tests
let results = vec![
AuditResult::pass("websocket_connection", "Connected successfully"),
AuditResult::fail("invalid_event", "Expected rejection, got acceptance"),
];
// Report
for result in &results {
println!("{}", result);
}
// Summary
let passed = results.iter().filter(|r| r.is_pass()).count();
let total = results.len();
println!("Results: {}/{} passed ({:.1}%)",
passed, total, (passed as f64 / total as f64) * 100.0);
```
---
## CLI Design
### Command Structure
```bash
grasp-audit audit [OPTIONS]
Options:
--relay <URL> Relay to test (required)
--mode <MODE> ci or production (default: ci)
--run-id <ID> Custom run ID (production mode only)
--spec <SPEC> Test spec to run (default: all)
--verbose Detailed output
```
### Usage Examples
```bash
# CI mode - quick smoke test
grasp-audit audit \
--relay ws://localhost:7000 \
--mode ci \
--spec nip01-smoke
# Production mode - full compliance audit
grasp-audit audit \
--relay wss://relay.example.com \
--mode production \
--run-id "audit-2025-11-04" \
--verbose
# Test all specs
grasp-audit audit --relay ws://localhost:7000
```
---
## Lessons Learned
### 1. Tag Migration is Breaking
**Lesson:** Changing tag structure breaks event queries.
**Impact:** Events created with old tags won't be found by new queries.
**Mitigation:**
- ✅ Accept breaking changes in alpha stage
- ✅ Document migration clearly
- ✅ Old events auto-expire via cleanup
- ✅ No production deployments affected
**Reference:** `docs/archive/2025-11-04-tag-migration.md`
---
### 2. Test Data Lifecycle Matters
**Lesson:** Test events accumulate and pollute relay.
**Solution:** Built-in cleanup strategy from day one.
**Implementation:**
- Every event has cleanup timestamp
- Relay can cleanup expired events
- No deletion event pollution (direct DB cleanup)
---
### 3. Isolation Enables Parallel Testing
**Lesson:** Unique run IDs enable parallel test execution.
**Benefit:** CI/CD can run multiple test suites simultaneously.
**Pattern:**
```rust
// Each CI run gets unique ID
let config = AuditConfig::ci();
// run_id = "ci-{uuid}"
// Tests isolated by run ID
let events = client.query().await?;
// Only returns events for this run
```
---
### 4. Standards Compliance Reduces Friction
**Lesson:** Using standard NIP-01 "t" tags instead of custom tags.
**Benefits:**
- ✅ No conflicts with other systems
- ✅ Standard relay filtering works
- ✅ Better interoperability
- ✅ Self-documenting
---
## Future Enhancements
### Planned Features
- [ ] **GRASP-01 Test Suite**: Repository announcement and state event tests
- [ ] **Test Report Generation**: JSON/HTML output for CI/CD
- [ ] **Performance Benchmarks**: Measure relay performance
- [ ] **Relay Comparison**: Side-by-side compliance comparison
- [ ] **Continuous Monitoring**: Periodic production audits
---
### Possible Improvements
- [ ] **Parallel Test Execution**: Run specs in parallel
- [ ] **Retry Logic**: Handle transient failures
- [ ] **Custom Assertions**: Domain-specific test helpers
- [ ] **Event Diff Tool**: Compare expected vs actual events
- [ ] **Cleanup Automation**: Auto-cleanup after tests
---
## Common Issues
### Issue: Integration Tests Fail
**Symptoms:** Tests timeout or fail to connect
**Causes:**
1. No relay running
2. Wrong relay URL
3. Firewall blocking connection
**Solution:**
```bash
# Start relay
docker run --rm -p 7000:7000 scsibug/nostr-rs-relay
# Verify relay is running
curl http://localhost:7000
# Run tests
cargo test -- --ignored
```
---
### Issue: Events Not Found in Query
**Symptoms:** Query returns empty even though events were sent
**Causes:**
1. Wrong run ID (querying different run)
2. Connection timing (query before event propagated)
3. Tag mismatch (uppercase vs lowercase)
**Solution:**
```rust
// Use same config for send and query
let config = AuditConfig::ci();
// Wait for event to propagate
tokio::time::sleep(Duration::from_millis(500)).await;
// Verify tags match exactly
let t_tag = SingleLetterTag::lowercase(Alphabet::T); // Lowercase!
```
---
### Issue: Build Fails in CI
**Symptoms:** `cargo build` fails with dependency errors
**Cause:** Not in Nix dev environment
**Solution:**
```bash
# Enter Nix environment first
cd grasp-audit
nix develop
# Then build
cargo build
```
---
## Quick Reference
### Configuration
```rust
// CI mode
let config = AuditConfig::ci();
// Production mode
let config = AuditConfig::production("run-id");
```
### Event Creation
```rust
let event = AuditEventBuilder::new(&config, kind, content)
.build(&keys)?;
```
### Client Usage
```rust
let client = AuditClient::new(config, keys);
client.add_relay("ws://localhost:7000").await?;
client.connect().await;
let events = client.query().await?;
```
### Running Tests
```bash
# Unit tests
cargo test --lib
# Integration tests
cargo test -- --ignored
# CLI
cargo run -- audit --relay ws://localhost:7000
```
---
## References
- **GRASP Protocol**: https://gitworkshop.dev/danconwaydev.com/grasp
- **NIP-01**: https://github.com/nostr-protocol/nips/blob/master/01.md
- **NIP-34**: https://github.com/nostr-protocol/nips/blob/master/34.md
- **grasp-audit README**: `grasp-audit/README.md`
- **Tag Migration**: `docs/archive/2025-11-04-tag-migration.md`
---
*Last updated: November 4, 2025*
*Status: Living document - update as grasp-audit evolves*
|