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
|
package auth
import (
"context"
"encoding/base64"
"encoding/json"
"testing"
"time"
"google.golang.org/grpc/metadata"
"code.northwest.io/nostr"
)
func TestNostrCredentials(t *testing.T) {
key, err := nostr.GenerateKey()
if err != nil {
t.Fatalf("failed to generate key: %v", err)
}
creds := NewNostrCredentials(key)
// Test GetRequestMetadata
ctx := context.Background()
uri := "https://example.com/nostr.v1.NostrRelay/PublishEvent"
md, err := creds.GetRequestMetadata(ctx, uri)
if err != nil {
t.Fatalf("GetRequestMetadata failed: %v", err)
}
// Check authorization header exists
authHeader, ok := md["authorization"]
if !ok {
t.Fatal("missing authorization header")
}
// Parse and validate the event
event, err := ParseAuthHeader(authHeader)
if err != nil {
t.Fatalf("failed to parse auth header: %v", err)
}
if event.Kind != 27235 {
t.Errorf("wrong event kind: got %d, want 27235", event.Kind)
}
if event.PubKey != key.Public() {
t.Error("pubkey mismatch")
}
if !event.Verify() {
t.Error("event signature verification failed")
}
// Check tags
uTag := event.Tags.Find("u")
if uTag == nil {
t.Fatal("missing 'u' tag")
}
if uTag.Value() != uri {
t.Errorf("wrong URI in tag: got %s, want %s", uTag.Value(), uri)
}
methodTag := event.Tags.Find("method")
if methodTag == nil {
t.Fatal("missing 'method' tag")
}
if methodTag.Value() != "POST" {
t.Errorf("wrong method in tag: got %s, want POST", methodTag.Value())
}
}
func TestParseAuthHeader(t *testing.T) {
tests := []struct {
name string
header string
wantErr bool
}{
{
name: "empty header",
header: "",
wantErr: true,
},
{
name: "missing prefix",
header: "Bearer token",
wantErr: true,
},
{
name: "invalid base64",
header: "Nostr not-base64!",
wantErr: true,
},
{
name: "invalid json",
header: "Nostr " + base64.StdEncoding.EncodeToString([]byte("not json")),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := ParseAuthHeader(tt.header)
if (err != nil) != tt.wantErr {
t.Errorf("ParseAuthHeader() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestValidateAuthEvent(t *testing.T) {
key, _ := nostr.GenerateKey()
// Create a valid event
event := &nostr.Event{
PubKey: key.Public(),
CreatedAt: time.Now().Unix(),
Kind: 27235,
Tags: nostr.Tags{
{"u", "https://example.com/test"},
{"method", "POST"},
},
Content: "",
}
key.Sign(event)
tests := []struct {
name string
event *nostr.Event
opts ValidationOptions
wantErr bool
}{
{
name: "valid event",
event: event,
opts: ValidationOptions{
TimestampWindow: 60,
ExpectedURI: "https://example.com/test",
ExpectedMethod: "POST",
},
wantErr: false,
},
{
name: "wrong kind",
event: &nostr.Event{
Kind: 1,
CreatedAt: time.Now().Unix(),
Tags: nostr.Tags{},
},
opts: ValidationOptions{},
wantErr: true,
},
{
name: "old timestamp",
event: &nostr.Event{
PubKey: key.Public(),
CreatedAt: time.Now().Unix() - 120, // 2 minutes ago
Kind: 27235,
Tags: nostr.Tags{},
Sig: event.Sig,
},
opts: ValidationOptions{
TimestampWindow: 60, // Only accept 60 seconds
},
wantErr: true,
},
{
name: "URI mismatch",
event: event,
opts: ValidationOptions{
TimestampWindow: 60,
ExpectedURI: "https://different.com/test",
},
wantErr: true,
},
{
name: "method mismatch",
event: event,
opts: ValidationOptions{
TimestampWindow: 60,
ExpectedMethod: "GET",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateAuthEvent(tt.event, tt.opts)
if (err != nil) != tt.wantErr {
t.Errorf("ValidateAuthEvent() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestPubkeyFromContext(t *testing.T) {
ctx := context.Background()
// Test empty context
pubkey, ok := PubkeyFromContext(ctx)
if ok {
t.Error("expected ok=false for empty context")
}
if pubkey != "" {
t.Error("expected empty pubkey for empty context")
}
// Test context with pubkey
expectedPubkey := "test-pubkey-123"
ctx = context.WithValue(ctx, pubkeyContextKey, expectedPubkey)
pubkey, ok = PubkeyFromContext(ctx)
if !ok {
t.Error("expected ok=true for context with pubkey")
}
if pubkey != expectedPubkey {
t.Errorf("got pubkey %s, want %s", pubkey, expectedPubkey)
}
}
func TestValidateAuthFromContext(t *testing.T) {
key, _ := nostr.GenerateKey()
// Create valid auth event
event := &nostr.Event{
PubKey: key.Public(),
CreatedAt: time.Now().Unix(),
Kind: 27235,
Tags: nostr.Tags{
{"u", "https://example.com/test"},
{"method", "POST"},
},
Content: "",
}
key.Sign(event)
eventJSON, _ := json.Marshal(event)
authHeader := "Nostr " + base64.StdEncoding.EncodeToString(eventJSON)
// Create context with metadata
md := metadata.Pairs("authorization", authHeader)
ctx := metadata.NewIncomingContext(context.Background(), md)
opts := &InterceptorOptions{
Read: AuthOperationConfig{
Enabled: true,
AllowedNpubs: nil,
},
Write: AuthOperationConfig{
Enabled: true,
AllowedNpubs: nil,
},
TimestampWindow: 60,
}
pubkey, err := validateAuthFromContext(ctx, "/test.Service/Method", opts)
if err != nil {
t.Fatalf("validateAuthFromContext failed: %v", err)
}
if pubkey != key.Public() {
t.Errorf("got pubkey %s, want %s", pubkey, key.Public())
}
}
func TestShouldSkipAuth(t *testing.T) {
skipMethods := []string{
"/health/Check",
"/nostr.v1.NostrRelay/GetInfo",
}
tests := []struct {
method string
want bool
}{
{"/health/Check", true},
{"/nostr.v1.NostrRelay/GetInfo", true},
{"/nostr.v1.NostrRelay/PublishEvent", false},
{"/other/Method", false},
}
for _, tt := range tests {
t.Run(tt.method, func(t *testing.T) {
got := shouldSkipAuth(tt.method, skipMethods)
if got != tt.want {
t.Errorf("shouldSkipAuth(%s) = %v, want %v", tt.method, got, tt.want)
}
})
}
}
func TestHashPayload(t *testing.T) {
payload := []byte("test payload")
hash := HashPayload(payload)
// Should be a 64-character hex string (SHA256)
if len(hash) != 64 {
t.Errorf("hash length = %d, want 64", len(hash))
}
// Same payload should produce same hash
hash2 := HashPayload(payload)
if hash != hash2 {
t.Error("same payload produced different hashes")
}
// Different payload should produce different hash
hash3 := HashPayload([]byte("different payload"))
if hash == hash3 {
t.Error("different payloads produced same hash")
}
}
func TestIsWriteMethod(t *testing.T) {
tests := []struct {
method string
want bool
}{
// Write methods
{"/nostr.v1.NostrRelay/PublishEvent", true},
{"/nostr.v1.NostrRelay/PublishBatch", true},
// Read methods
{"/nostr.v1.NostrRelay/Subscribe", false},
{"/nostr.v1.NostrRelay/Unsubscribe", false},
{"/nostr.v1.NostrRelay/QueryEvents", false},
{"/nostr.v1.NostrRelay/CountEvents", false},
// Edge cases
{"", false},
{"/", false},
}
for _, tt := range tests {
t.Run(tt.method, func(t *testing.T) {
got := isWriteMethod(tt.method)
if got != tt.want {
t.Errorf("isWriteMethod(%q) = %v, want %v", tt.method, got, tt.want)
}
})
}
}
|