-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathexample_db_authenticate_test.go
More file actions
568 lines (485 loc) · 18.3 KB
/
Copy pathexample_db_authenticate_test.go
File metadata and controls
568 lines (485 loc) · 18.3 KB
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package surrealdb_test
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
surrealdb "github.com/surrealdb/surrealdb.go"
"github.com/surrealdb/surrealdb.go/contrib/testenv"
"github.com/surrealdb/surrealdb.go/pkg/models"
)
// nolint:gocyclo // Example covers end-to-end JWT setup; splitting would reduce readability for docs
func ExampleDB_Authenticate_jwt_databaseLevelUser() {
ctx := context.Background()
// Generate ECDSA key pair using Go standard library
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
panic(fmt.Sprintf("Failed to generate private key: %v", err))
}
// Extract public key and encode it to PEM format
publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
panic(fmt.Sprintf("Failed to marshal public key: %v", err))
}
publicKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
})
// Connect to SurrealDB and authenticate as root
db, err := surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
db, err = testenv.Init(db, "exampledb_authenticate_jwt", "testdb", "user")
if err != nil {
panic(err)
}
// Sign in as root to set up the JWT access method
_, err = db.SignIn(ctx, surrealdb.Auth{
Username: "root",
Password: "root",
})
if err != nil {
panic(fmt.Sprintf("SignIn as root failed: %v", err))
}
err = db.Use(ctx, "exampledb_authenticate_jwt", "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed: %v", err))
}
// Remove any existing access method first
_, err = surrealdb.Query[any](ctx, db, `REMOVE ACCESS IF EXISTS jwt_access ON DATABASE`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to remove existing JWT access: %v", err))
}
// Define a JWT access method with the public key
defineAccessQuery := fmt.Sprintf(`
DEFINE ACCESS jwt_access ON DATABASE TYPE JWT
ALGORITHM ES256 KEY '%s'
`, string(publicKeyPEM))
_, err = surrealdb.Query[any](ctx, db, defineAccessQuery, nil)
if err != nil {
panic(fmt.Sprintf("Failed to define JWT access: %v", err))
}
// Create the user table and a test user record for SurrealDB 3.x
// SurrealDB 3.x requires the table to exist before querying,
// while SurrealDB 2.x does not.
_, err = surrealdb.Query[any](ctx, db, `
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
CREATE user:test SET name = "test_user"
`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to create test user: %v", err))
}
// Create a signed JWT token using the private key
// Only the required claims for database-level JWT access
// See: https://surrealdb.com/docs/surrealql/statements/define/access/jwt#using-tokens
claims := jwt.MapClaims{
"exp": time.Now().Add(1 * time.Hour).Unix(), // Token expiration
"ac": "jwt_access", // Access method name
"ns": "exampledb_authenticate_jwt", // Namespace
"db": "testdb", // Database
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
signedToken, err := token.SignedString(privateKey)
if err != nil {
panic(fmt.Sprintf("Failed to sign JWT token: %v", err))
}
// Close the root connection
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
// Create a new connection and authenticate with the JWT token
db, err = surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
// Authenticate using the JWT token via the Authenticate method
// The JWT contains ns and db claims, so we don't need to call Use() first
err = db.Authenticate(ctx, signedToken)
if err != nil {
panic(fmt.Sprintf("Authenticate with JWT failed: %v", err))
}
// Verify authentication by performing a query
results, err := surrealdb.Query[any](ctx, db, `SELECT * FROM $id`, map[string]any{
"id": models.NewRecordID("user", "test"),
})
if err != nil {
panic(fmt.Sprintf("Query after JWT authentication failed: %v", err))
}
if results == nil || len(*results) == 0 {
panic("Expected query results after JWT authentication")
}
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
fmt.Println("JWT-based authentication completed successfully")
// Output:
// JWT-based authentication completed successfully
}
//nolint:gocyclo // Example functions are necessarily complex to demonstrate complete workflows
func ExampleDB_Authenticate_jwt_hs512_databaseLevelUser() {
ctx := context.Background()
// Generate a symmetric key for HS512 (HMAC-SHA512)
// Use a strong random string as the symmetric key
symmetricKeyString := "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8" //nolint:goconst // duplicated across examples intentionally for self-contained docs
// Connect to SurrealDB and authenticate as root
db, err := surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
db, err = testenv.Init(db, "exampledb_authenticate_jwt_hs512", "testdb", "user")
if err != nil {
panic(err)
}
// Sign in as root to set up the JWT access method
_, err = db.SignIn(ctx, surrealdb.Auth{
Username: "root",
Password: "root",
})
if err != nil {
panic(fmt.Sprintf("SignIn as root failed: %v", err))
}
err = db.Use(ctx, "exampledb_authenticate_jwt_hs512", "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed: %v", err))
}
// Remove any existing access method first
_, err = surrealdb.Query[any](ctx, db, `REMOVE ACCESS IF EXISTS jwt_hs512 ON DATABASE`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to remove existing JWT access: %v", err))
}
// Define a JWT access method with HS512 and the symmetric key
// See: https://surrealdb.com/docs/surrealql/statements/define/access/jwt#database
defineAccessQuery := fmt.Sprintf(`
DEFINE ACCESS jwt_hs512 ON DATABASE TYPE JWT
ALGORITHM HS512 KEY '%s'
`, symmetricKeyString)
_, err = surrealdb.Query[any](ctx, db, defineAccessQuery, nil)
if err != nil {
panic(fmt.Sprintf("Failed to define JWT access: %v", err))
}
// Create the user table and a test user record for SurrealDB 3.x
// SurrealDB 3.x requires the table to exist before querying,
// while SurrealDB 2.x does not.
_, err = surrealdb.Query[any](ctx, db, `
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
CREATE user:test SET name = "test_user"
`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to create test user: %v", err))
}
// Create a signed JWT token using the symmetric key
// Only the required claims for database-level JWT access
claims := jwt.MapClaims{
"exp": time.Now().Add(1 * time.Hour).Unix(), // Token expiration
"ac": "jwt_hs512", // Access method name
"ns": "exampledb_authenticate_jwt_hs512", // Namespace
"db": "testdb", // Database
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
signedToken, err := token.SignedString([]byte(symmetricKeyString))
if err != nil {
panic(fmt.Sprintf("Failed to sign JWT token: %v", err))
}
// Close the root connection
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
// Create a new connection and authenticate with the JWT token
db, err = surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
// Authenticate using the JWT token via the Authenticate method
// The JWT contains ns and db claims, so we don't need to call Use() first
err = db.Authenticate(ctx, signedToken)
if err != nil {
panic(fmt.Sprintf("Authenticate with JWT failed: %v", err))
}
// Verify authentication by performing a query
results, err := surrealdb.Query[any](ctx, db, `SELECT * FROM $id`, map[string]any{
"id": models.NewRecordID("user", "test"),
})
if err != nil {
panic(fmt.Sprintf("Query after JWT authentication failed: %v", err))
}
if results == nil || len(*results) == 0 {
panic("Expected query results after JWT authentication")
}
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
fmt.Println("JWT HS512 authentication completed successfully")
// Output:
// JWT HS512 authentication completed successfully
}
// nolint:gocyclo // Example shows full flow for namespace-level JWT auth
func ExampleDB_Authenticate_jwt_hs512_namespaceLevelUser() {
ctx := context.Background()
// Symmetric key for HS512 (HMAC-SHA512)
symmetricKeyString := "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8" //nolint:goconst // duplicated across examples intentionally for self-contained docs
// Names for this test
ns := "exampledb_authenticate_jwt_hs512_ns"
accessName := "jwt_hs512_ns"
// Connect to SurrealDB and authenticate as root
db, err := surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
db, err = testenv.Init(db, ns, "testdb")
if err != nil {
panic(err)
}
// Sign in as root to set up the JWT access method
_, err = db.SignIn(ctx, surrealdb.Auth{
Username: "root",
Password: "root",
})
if err != nil {
panic(fmt.Sprintf("SignIn as root failed: %v", err))
}
// Select namespace (database may be required by helper; safe to set anyway)
err = db.Use(ctx, ns, "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed: %v", err))
}
// Remove any existing access method first (namespace level)
_, err = surrealdb.Query[any](ctx, db, `REMOVE ACCESS IF EXISTS jwt_hs512_ns ON NAMESPACE`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to remove existing JWT access: %v", err))
}
// Define a JWT access method for namespace level with HS512
defineAccessQuery := fmt.Sprintf(`
DEFINE ACCESS %s ON NAMESPACE TYPE JWT
ALGORITHM HS512 KEY '%s'
`, accessName, symmetricKeyString)
_, err = surrealdb.Query[any](ctx, db, defineAccessQuery, nil)
if err != nil {
panic(fmt.Sprintf("Failed to define JWT access: %v", err))
}
// Create a database and user table/record for the namespace-level auth test
// SurrealDB 3.x requires the table to exist before querying,
// while SurrealDB 2.x does not.
// First remove the database if it exists to ensure clean state
_, _ = surrealdb.Query[any](ctx, db, `REMOVE DATABASE IF EXISTS testdb`, nil)
_, err = surrealdb.Query[any](ctx, db, `
DEFINE DATABASE testdb;
USE DB testdb;
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
CREATE user:test SET name = "test_user"
`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to create test user: %v", err))
}
// Create a signed JWT token using the symmetric key (namespace-level claims)
claims := jwt.MapClaims{
"exp": time.Now().Add(1 * time.Hour).Unix(),
"ac": accessName,
"ns": ns,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
signedToken, err := token.SignedString([]byte(symmetricKeyString))
if err != nil {
panic(fmt.Sprintf("Failed to sign JWT token: %v", err))
}
// Close the root connection
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
// Create a new connection and authenticate with the JWT token
db, err = surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
// Authenticate using the JWT token via the Authenticate method
err = db.Authenticate(ctx, signedToken)
if err != nil {
panic(fmt.Sprintf("Authenticate with JWT failed: %v", err))
}
// For namespace-level tokens, select a database to run queries
err = db.Use(ctx, ns, "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed after JWT auth: %v", err))
}
// Verify authentication by performing a query
results, err := surrealdb.Query[any](ctx, db, `SELECT * FROM $id`, map[string]any{
"id": models.NewRecordID("user", "test"),
})
if err != nil {
panic(fmt.Sprintf("Query after JWT authentication failed: %v", err))
}
if results == nil || len(*results) == 0 {
panic("Expected query results after JWT authentication")
}
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
fmt.Println("JWT HS512 namespace-level authentication completed successfully")
// Output:
// JWT HS512 namespace-level authentication completed successfully
}
// nolint:gocyclo // Example shows full flow for root-level JWT auth
func ExampleDB_Authenticate_jwt_hs512_rootLevelUser() {
ctx := context.Background()
symmetricKeyString := "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8" //nolint:goconst // duplicated across examples intentionally for self-contained docs
accessName := "jwt_hs512_root"
ns := "exampledb_authenticate_jwt_hs512_root"
// Admin connection
db, err := surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
db, err = testenv.Init(db, ns, "testdb")
if err != nil {
panic(err)
}
if _, err = db.SignIn(ctx, surrealdb.Auth{Username: "root", Password: "root"}); err != nil {
panic(fmt.Sprintf("SignIn as root failed: %v", err))
}
err = db.Use(ctx, ns, "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed: %v", err))
}
_, err = surrealdb.Query[any](ctx, db, `REMOVE ACCESS IF EXISTS jwt_hs512_root ON ROOT`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to remove existing JWT access: %v", err))
}
defineAccessQuery := fmt.Sprintf(`
DEFINE ACCESS %s ON ROOT TYPE JWT
ALGORITHM HS512 KEY '%s'
`, accessName, symmetricKeyString)
_, err = surrealdb.Query[any](ctx, db, defineAccessQuery, nil)
if err != nil {
panic(fmt.Sprintf("Failed to define JWT access: %v", err))
}
// Create the namespace, database, table, and test user for root-level auth test
// SurrealDB 3.x requires the table to exist before querying,
// while SurrealDB 2.x does not.
// First remove namespace if it exists to ensure clean state
_, _ = surrealdb.Query[any](ctx, db, fmt.Sprintf(`REMOVE NAMESPACE IF EXISTS %s`, ns), nil)
_, err = surrealdb.Query[any](ctx, db, fmt.Sprintf(`
DEFINE NAMESPACE %s;
USE NS %s;
DEFINE DATABASE testdb;
USE DB testdb;
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
CREATE user:test SET name = "test_user"
`, ns, ns), nil)
if err != nil {
panic(fmt.Sprintf("Failed to create test user: %v", err))
}
// Root-level token claims (no ns/db)
claims := jwt.MapClaims{
"exp": time.Now().Add(1 * time.Hour).Unix(),
"ac": accessName,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
signedToken, err := token.SignedString([]byte(symmetricKeyString))
if err != nil {
panic(fmt.Sprintf("Failed to sign JWT token: %v", err))
}
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
// Authenticate with root-level token
db, err = surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
err = db.Authenticate(ctx, signedToken)
if err != nil {
panic(fmt.Sprintf("Authenticate with JWT failed: %v", err))
}
// Choose ns/db for subsequent queries
err = db.Use(ctx, ns, "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed after JWT auth: %v", err))
}
results, err := surrealdb.Query[any](ctx, db, `SELECT * FROM $id`, map[string]any{
"id": models.NewRecordID("user", "test"),
})
if err != nil {
panic(fmt.Sprintf("Query after JWT authentication failed: %v", err))
}
if results == nil || len(*results) == 0 {
panic("Expected query results after JWT authentication")
}
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
fmt.Println("JWT HS512 root-level authentication completed successfully")
// Output:
// JWT HS512 root-level authentication completed successfully
}
func ExampleDB_Authenticate_jwt_hs512_rootLevelUser_expired() {
ctx := context.Background()
symmetricKeyString := "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8" //nolint:goconst // duplicated across examples intentionally for self-contained docs
accessName := "jwt_hs512_root_expired"
// Admin connection
db, err := surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
// Use a dedicated namespace for this test
ns := "exampledb_authenticate_jwt_hs512_root_expired"
db, err = testenv.Init(db, ns, "testdb")
if err != nil {
panic(err)
}
if _, err = db.SignIn(ctx, surrealdb.Auth{Username: "root", Password: "root"}); err != nil {
panic(fmt.Sprintf("SignIn as root failed: %v", err))
}
err = db.Use(ctx, ns, "testdb")
if err != nil {
panic(fmt.Sprintf("Use failed: %v", err))
}
_, err = surrealdb.Query[any](ctx, db, `REMOVE ACCESS IF EXISTS jwt_hs512_root_expired ON ROOT`, nil)
if err != nil {
panic(fmt.Sprintf("Failed to remove existing JWT access: %v", err))
}
defineAccessQuery := fmt.Sprintf(`
DEFINE ACCESS %s ON ROOT TYPE JWT
ALGORITHM HS512 KEY '%s'
`, accessName, symmetricKeyString)
_, err = surrealdb.Query[any](ctx, db, defineAccessQuery, nil)
if err != nil {
panic(fmt.Sprintf("Failed to define JWT access: %v", err))
}
// Expired token (exp in the past)
claims := jwt.MapClaims{
"exp": time.Now().Add(-1 * time.Hour).Unix(),
"ac": accessName,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
signedToken, err := token.SignedString([]byte(symmetricKeyString))
if err != nil {
panic(fmt.Sprintf("Failed to sign JWT token: %v", err))
}
if closeErr := db.Close(ctx); closeErr != nil {
panic(fmt.Sprintf("Failed to close the database connection: %v", closeErr))
}
// Try authenticating with expired token - should fail
db, err = surrealdb.FromEndpointURLString(ctx, testenv.GetSurrealDBWSURL())
if err != nil {
panic(err)
}
err = db.Authenticate(ctx, signedToken)
if err != nil {
// Expected failure path
fmt.Println("JWT HS512 root-level expired authentication failed as expected")
return
}
// If we reached here, authentication incorrectly succeeded
panic("Expected Authenticate to fail with expired token, but it succeeded")
// Output:
// JWT HS512 root-level expired authentication failed as expected
}