Skip to content

Commit feb7407

Browse files
committed
fix: address code review issues from PR #190
- Fix base64 concatenation bug in handleInitialRequest/Response - Fix certificate signing bug in certificate_debug.go - Fix TestPeerCertificateExchange with proper field encryption - Improve error handling consistency with NewAuthError - Fix variable naming for consistency
1 parent f3d9ec6 commit feb7407

File tree

3 files changed

+54
-31
lines changed

3 files changed

+54
-31
lines changed

auth/peer.go

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -494,15 +494,21 @@ func (p *Peer) handleInitialRequest(ctx context.Context, message *AuthMessage, s
494494
Certificates: certs,
495495
}
496496

497-
data := message.InitialNonce + session.SessionNonce
498-
sigData, err := base64.StdEncoding.DecodeString(data)
497+
// Decode the nonces first before concatenating
498+
initialNonceBytes, err := base64.StdEncoding.DecodeString(message.InitialNonce)
499499
if err != nil {
500-
return NewAuthError("failed to prepare data to sign", err)
500+
return NewAuthError("failed to decode initial nonce", err)
501501
}
502+
sessionNonceBytes, err := base64.StdEncoding.DecodeString(session.SessionNonce)
503+
if err != nil {
504+
return NewAuthError("failed to decode session nonce", err)
505+
}
506+
// Concatenate the decoded bytes
507+
sigData := append(initialNonceBytes, sessionNonceBytes...)
502508

503509
keyID := fmt.Sprintf("%s %s", message.InitialNonce, session.SessionNonce)
504510

505-
arg := wallet.CreateSignatureArgs{
511+
args := wallet.CreateSignatureArgs{
506512
EncryptionArgs: wallet.EncryptionArgs{
507513
ProtocolID: wallet.Protocol{
508514
// SecurityLevel set to 2 (SecurityLevelEveryAppAndCounterparty) as specified in BRC-31 (Authrite)
@@ -515,13 +521,12 @@ func (p *Peer) handleInitialRequest(ctx context.Context, message *AuthMessage, s
515521
Counterparty: message.IdentityKey,
516522
},
517523
},
518-
// Sign the certificate request data, as in TypeScript
519524
Data: sigData,
520525
}
521526

522-
sigResult, err := p.wallet.CreateSignature(ctx, arg, "")
527+
sigResult, err := p.wallet.CreateSignature(ctx, args, "")
523528
if err != nil {
524-
return fmt.Errorf("failed to sign initial response: %w", err)
529+
return NewAuthError("failed to sign initial response", err)
525530
}
526531

527532
response.Signature = sigResult.Signature.Serialize()
@@ -545,16 +550,21 @@ func (p *Peer) handleInitialResponse(ctx context.Context, message *AuthMessage,
545550
return ErrSessionNotFound
546551
}
547552

548-
data := message.InitialNonce + session.SessionNonce
549-
550-
sigData, err := base64.StdEncoding.DecodeString(data)
553+
// Decode the nonces first before concatenating
554+
initialNonceBytes, err := base64.StdEncoding.DecodeString(message.InitialNonce)
555+
if err != nil {
556+
return NewAuthError("failed to decode initial nonce", err)
557+
}
558+
sessionNonceBytes, err := base64.StdEncoding.DecodeString(session.SessionNonce)
551559
if err != nil {
552-
return NewAuthError("failed to prepare data to sign", err)
560+
return NewAuthError("failed to decode session nonce", err)
553561
}
562+
// Concatenate the decoded bytes
563+
sigData := append(initialNonceBytes, sessionNonceBytes...)
554564

555565
signature, err := ec.ParseSignature(message.Signature)
556566
if err != nil {
557-
return fmt.Errorf("failed to parse signature: %w", err)
567+
return NewAuthError("failed to parse signature", err)
558568
}
559569

560570
verifyResult, err := p.wallet.VerifySignature(ctx, wallet.VerifySignatureArgs{
@@ -612,13 +622,13 @@ func (p *Peer) handleInitialResponse(ctx context.Context, message *AuthMessage,
612622
utilsRequestedCerts,
613623
)
614624
if err != nil {
615-
return fmt.Errorf("invalid certificates: %w", err)
625+
return NewAuthError("invalid certificates", err)
616626
}
617627

618628
for _, callback := range p.onCertificateReceivedCallbacks {
619629
err := callback(senderPublicKey, message.Certificates)
620630
if err != nil {
621-
return fmt.Errorf("certificate received callback error: %w", err)
631+
return NewAuthError("certificate received callback error", err)
622632
}
623633
}
624634
}
@@ -638,7 +648,7 @@ func (p *Peer) handleInitialResponse(ctx context.Context, message *AuthMessage,
638648
if len(message.RequestedCertificates.Certifiers) > 0 || len(message.RequestedCertificates.CertificateTypes) > 0 {
639649
err = p.sendCertificates(ctx, message)
640650
if err != nil {
641-
return fmt.Errorf("failed to send requested certificates: %w", err)
651+
return NewAuthError("failed to send requested certificates", err)
642652
}
643653
}
644654

@@ -712,7 +722,7 @@ func (p *Peer) handleCertificateRequest(ctx context.Context, message *AuthMessag
712722
// Try to parse the signature
713723
signature, err := ec.ParseSignature(message.Signature)
714724
if err != nil {
715-
return fmt.Errorf("failed to parse signature: %w", err)
725+
return NewAuthError("failed to parse signature", err)
716726
}
717727

718728
// Verify signature
@@ -740,7 +750,7 @@ func (p *Peer) handleCertificateRequest(ctx context.Context, message *AuthMessag
740750
if len(message.RequestedCertificates.Certifiers) > 0 || len(message.RequestedCertificates.CertificateTypes) > 0 {
741751
err = p.sendCertificates(ctx, message)
742752
if err != nil {
743-
return fmt.Errorf("failed to send requested certificates: %w", err)
753+
return NewAuthError("failed to send requested certificates", err)
744754
}
745755
}
746756

@@ -776,7 +786,7 @@ func (p *Peer) handleCertificateResponse(ctx context.Context, message *AuthMessa
776786
// Try to parse the signature
777787
signature, err := ec.ParseSignature(message.Signature)
778788
if err != nil {
779-
return fmt.Errorf("failed to parse signature: %w", err)
789+
return NewAuthError("failed to parse signature", err)
780790
}
781791

782792
// Verify signature
@@ -865,7 +875,7 @@ func (p *Peer) handleGeneralMessage(ctx context.Context, message *AuthMessage, s
865875
// Try to parse the signature
866876
signature, err := ec.ParseSignature(message.Signature)
867877
if err != nil {
868-
return fmt.Errorf("failed to parse signature: %w", err)
878+
return NewAuthError("failed to parse signature", err)
869879
}
870880

871881
// Verify signature

auth/peer_test.go

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,6 @@ func (t *LoggingMockTransport) OnData(callback func(context.Context, *AuthMessag
405405

406406
// TestPeerCertificateExchange tests certificate request and exchange
407407
func TestPeerCertificateExchange(t *testing.T) {
408-
t.Skip("Needs a fix for DecryptFields - probably something in test setup need to be adjusted")
409408

410409
var certType = tu.GetByte32FromString("testCertType")
411410
requiredField := "testField"
@@ -451,13 +450,26 @@ func TestPeerCertificateExchange(t *testing.T) {
451450
return &wallet.VerifySignatureResult{Valid: true}, nil
452451
}
453452

454-
// Create raw certificates with proper base64 encoding using our helper
453+
// Generate a symmetric key for field encryption
454+
fieldSymmetricKeyBytes := make([]byte, 32)
455+
for i := range fieldSymmetricKeyBytes {
456+
fieldSymmetricKeyBytes[i] = byte(i) // Deterministic for testing
457+
}
458+
fieldSymmetricKey := ec.NewSymmetricKey(fieldSymmetricKeyBytes)
459+
460+
// Encrypt the field value
461+
plainFieldValue := []byte("decrypted field value")
462+
encryptedFieldBytes, err := fieldSymmetricKey.Encrypt(plainFieldValue)
463+
require.NoError(t, err)
464+
encryptedFieldValue := base64.StdEncoding.EncodeToString(encryptedFieldBytes)
465+
466+
// Create raw certificates with encrypted fields
455467
aliceCertRaw := wallet.Certificate{
456468
Type: certType,
457469
SerialNumber: tu.GetByte32FromString("serial1"),
458470
Subject: aliceSubject,
459471
Certifier: bobSubject,
460-
Fields: map[string]string{requiredField: "fieldValue"},
472+
Fields: map[string]string{requiredField: encryptedFieldValue},
461473
RevocationOutpoint: tu.OutpointFromString(t, "a755810c21e17183ff6db6685f0de239fd3a0a3c0d4ba7773b0b0d1748541e2b.0"),
462474
}
463475

@@ -466,7 +478,7 @@ func TestPeerCertificateExchange(t *testing.T) {
466478
SerialNumber: tu.GetByte32FromString("serial2"),
467479
Subject: bobSubject,
468480
Certifier: aliceSubject,
469-
Fields: map[string]string{requiredField: "fieldValue"},
481+
Fields: map[string]string{requiredField: encryptedFieldValue},
470482
RevocationOutpoint: tu.OutpointFromString(t, "a755810c21e17183ff6db6685f0de239fd3a0a3c0d4ba7773b0b0d1748541e2b.1"),
471483
}
472484

@@ -510,28 +522,29 @@ func TestPeerCertificateExchange(t *testing.T) {
510522
logger.Printf("DEBUG: Alice cert signature: %x", aliceCert.Signature)
511523
logger.Printf("DEBUG: Bob cert signature: %x", bobCert.Signature)
512524

513-
// Create mock keyring results - also properly encoded
514-
fieldValueBase64 := base64.StdEncoding.EncodeToString([]byte("key-for-field"))
525+
// Mock keyring - in real usage this would be the symmetric key encrypted for the verifier
526+
// For testing, we just need valid encrypted data that MockDecrypt can "decrypt" to fieldSymmetricKeyBytes
527+
encryptedSymmetricKey := base64.StdEncoding.EncodeToString(fieldSymmetricKeyBytes)
515528
aliceWallet.MockProveCertificate = func(ctx context.Context, args wallet.ProveCertificateArgs, originator string) (*wallet.ProveCertificateResult, error) {
516529
return &wallet.ProveCertificateResult{
517-
KeyringForVerifier: map[string]string{requiredField: fieldValueBase64},
530+
KeyringForVerifier: map[string]string{requiredField: encryptedSymmetricKey},
518531
}, nil
519532
}
520533
bobWallet.MockProveCertificate = func(ctx context.Context, args wallet.ProveCertificateArgs, originator string) (*wallet.ProveCertificateResult, error) {
521534
return &wallet.ProveCertificateResult{
522-
KeyringForVerifier: map[string]string{requiredField: fieldValueBase64},
535+
KeyringForVerifier: map[string]string{requiredField: encryptedSymmetricKey},
523536
}, nil
524537
}
525538

526-
// Configure wallet mocks for Decrypt to make DecryptFields work
539+
// MockDecrypt returns the symmetric key for field decryption
527540
aliceWallet.MockDecrypt = func(ctx context.Context, args wallet.DecryptArgs, originator string) (*wallet.DecryptResult, error) {
528541
return &wallet.DecryptResult{
529-
Plaintext: []byte("decrypted field value"),
542+
Plaintext: fieldSymmetricKeyBytes,
530543
}, nil
531544
}
532545
bobWallet.MockDecrypt = func(ctx context.Context, args wallet.DecryptArgs, originator string) (*wallet.DecryptResult, error) {
533546
return &wallet.DecryptResult{
534-
Plaintext: []byte("decrypted field value"),
547+
Plaintext: fieldSymmetricKeyBytes,
535548
}, nil
536549
}
537550

auth/utils/certificate_debug.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ func SignCertificateWithWalletForTest(ctx context.Context, cert wallet.Certifica
8282
return encodedCert, fmt.Errorf("failed to get identity key of signer: %w", err)
8383
}
8484

85-
cert.Certifier = publicKeyResult.PublicKey
85+
encodedCert.Certifier = publicKeyResult.PublicKey
8686

8787
certObj, err := certificates.FromWalletCertificate(&encodedCert)
8888
if err != nil {

0 commit comments

Comments
 (0)