Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat (accounts/base): Add passkey support to base account type. #21755

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

baryon2
Copy link

@baryon2 baryon2 commented Sep 16, 2024

Description

This PR adds authn pubkey type to the base account that will make it possible to verify transactions signed using passkeys.

Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Introduced new data structures and functions to enhance authentication processes, including support for token binding and client data handling.
    • Added functionality for managing authentication public keys and verifying signatures.
    • Implemented a protocol buffer for authentication public keys to streamline key management.
  • Bug Fixes

    • Improved validation processes for public keys to ensure enhanced security during authentication.

1. Update amino name
2. Add comments in proto file
3. Fix lint issues.
Copy link
Contributor

coderabbitai bot commented Sep 16, 2024

Walkthrough

Walkthrough

The changes introduce new types and functions for handling authentication and client data in the Cosmos SDK. Key additions include structures for token binding and client data, along with functions for generating authentication keys and client data representations. A new file for managing authentication public keys is created, implementing signature verification. Additionally, a protocol buffer definition for authentication public keys is introduced, facilitating secure management of public keys associated with passkeys.

Changes

File Path Change Summary
x/accounts/defaults/base/account_test.go Added new types (CeremonyType, TokenBindingStatus, TokenBinding), structs (CollectedClientData), and functions (GenerateAuthnKey, GenerateClientData). Modified setupBaseAccount and added TestAuthenticateAuthn for authentication validation.
x/accounts/defaults/base/keys/authn/authn_pubkey.go Introduced Signature struct and AuthnPubKey struct with methods for public key handling and signature verification.
x/accounts/proto/cosmos/accounts/defaults/base/v1/keys/authn_pubkey.proto Defined authnpubkey message with fields for key_id and key for managing authentication public keys.

Possibly related PRs

Suggested labels

C:x/accounts/base, backport/v0.52.x

Suggested reviewers

  • aaronc
  • facundomedica
  • julienrbrt
  • akhilkumarpilli

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.


func (pubKey *AuthnPubKey) Address() cometcrypto.Address {
if len(pubKey.Key) != AuthnPubKeySize {
panic("length of pubkey is incorrect")

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
@baryon2 baryon2 marked this pull request as ready for review September 24, 2024 15:16
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Outside diff range and nitpick comments (3)
x/accounts/proto/cosmos/accounts/defaults/base/v1/keys/authn_pubkey.proto (1)

9-22: Consider renaming the message to follow PascalCase convention.

The message structure and fields look good, but the message name "authnpubkey" doesn't follow the typical PascalCase convention for protocol buffer messages. Consider renaming it to "AuthnPubKey" for consistency with common protobuf naming practices.

Here's the suggested change:

- message authnpubkey {
+ message AuthnPubKey {

The rest of the message structure, including field definitions and comments, looks good and provides clear information about the purpose of each field.

x/accounts/defaults/base/keys/authn/authn_pubkey.go (1)

62-123: Add unit tests for the VerifySignature method.

Unit tests are crucial for ensuring the correctness and security of cryptographic functions like VerifySignature. Please add comprehensive tests covering various scenarios, including valid and invalid signatures, incorrect encodings, and edge cases.

Do you want me to help generate unit test code or open a GitHub issue to track this task?

x/accounts/defaults/base/account_test.go (1)

64-64: Nitpick: Consider generating KeyId dynamically to avoid static analysis alerts

The hardcoded KeyId at line 64 may trigger static analysis tools to flag a potential API key exposure. Even though this is test code, generating the KeyId dynamically can help avoid unnecessary alerts and adhere to best practices.

Consider applying this change:

-        KeyId: "f482bd153df0ca2ea17d7b1e0178c14ff959628f",
+        KeyId: generateKeyId(pkBytes),

And define a generateKeyId function to compute the KeyId from pkBytes, such as by hashing the public key bytes.

Tools
Gitleaks

64-64: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f348d84 and 3e35f3a.

Files ignored due to path filters (1)
  • x/accounts/defaults/base/keys/authn/authn_pubkey.pb.go is excluded by !**/*.pb.go
Files selected for processing (3)
  • x/accounts/defaults/base/account_test.go (4 hunks)
  • x/accounts/defaults/base/keys/authn/authn_pubkey.go (1 hunks)
  • x/accounts/proto/cosmos/accounts/defaults/base/v1/keys/authn_pubkey.proto (1 hunks)
Additional context used
Path-based instructions (2)
x/accounts/defaults/base/account_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/accounts/defaults/base/keys/authn/authn_pubkey.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Gitleaks
x/accounts/defaults/base/account_test.go

64-64: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

GitHub Check: CodeQL
x/accounts/defaults/base/keys/authn/authn_pubkey.go

[warning] 40-40: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt

buf
x/accounts/proto/cosmos/accounts/defaults/base/v1/keys/authn_pubkey.proto

4-4: import "amino/amino.proto": file does not exist

(COMPILE)

Additional comments not posted (4)
x/accounts/proto/cosmos/accounts/defaults/base/v1/keys/authn_pubkey.proto (3)

2-2: LGTM: Package declaration and Go option are correct.

The package declaration and Go-specific option are properly set and follow the Cosmos SDK conventions.

Also applies to: 7-7


11-14: LGTM: Amino and GoGo options are correctly set.

The Amino and GoGo options are properly configured:

  1. The Amino name follows the Cosmos SDK naming convention.
  2. The Amino message encoding is appropriately set to "key_field".
  3. The GoGo option to disable the default stringer is correctly set, which is common in Cosmos SDK for custom string representations.

These options ensure proper integration with the Cosmos SDK's serialization and encoding systems.


1-5: Verify the existence of the "amino/amino.proto" file.

The static analysis tool indicates that the file "amino/amino.proto" does not exist. Please ensure that this file is present in the correct location within your project or dependency tree.

Run the following script to check for the existence of the file:

If the file is not found, consider updating the import statement or adding the missing file to your project.

Verification successful

Confirmed the existence of "proto/amino/amino.proto".

The file "amino/amino.proto" was found at "proto/amino/amino.proto", ensuring it is present in the codebase. The errors encountered when searching "vendor" and "go.mod" can be disregarded as these paths are not directories.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the existence of amino/amino.proto file

# Test: Search for amino/amino.proto file
fd -t f 'amino.proto' | grep 'amino/amino.proto'

# If the above command doesn't find the file, check in common dependency locations
echo "Checking in common dependency locations:"
fd -t f 'amino.proto' vendor go.mod

Length of output: 344

Tools
buf

4-4: import "amino/amino.proto": file does not exist

(COMPILE)

x/accounts/defaults/base/account_test.go (1)

341-479: Unit test TestAuthenticateAuthn provides comprehensive coverage

The test function TestAuthenticateAuthn effectively covers both successful authentication and failure scenarios with invalid signatures. This ensures that the new authentication mechanism is thoroughly tested for correctness and robustness.

Comment on lines +38 to +44
func (pubKey *AuthnPubKey) Address() cometcrypto.Address {
if len(pubKey.Key) != AuthnPubKeySize {
panic("length of pubkey is incorrect")
}

return address.Hash(proto.MessageName(pubKey), pubKey.Key)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid using panic in library code.

According to the Uber Go Style Guide, panics should be avoided in library code. Instead of panicking when the key length is incorrect, consider validating the key length upon creation of the AuthnPubKey instance or redesigning the method to return an error.

Tools
GitHub Check: CodeQL

[warning] 40-40: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt

Comment on lines +62 to +123
func (pubKey *AuthnPubKey) VerifySignature(msg, sigStr []byte) bool {
sig := Signature{}
err := json.Unmarshal(sigStr, &sig)
if err != nil {
return false
}

clientDataJSON, err := hex.DecodeString(sig.ClientDataJSON)
if err != nil {
return false
}

clientData := make(map[string]interface{})
err = json.Unmarshal(clientDataJSON, &clientData)
if err != nil {
return false
}

challengeBase64, ok := clientData["challenge"].(string)
if !ok {
return false
}
challenge, err := base64.RawURLEncoding.DecodeString(challengeBase64)
if err != nil {
return false
}

// Check challenge == msg
if !bytes.Equal(challenge, msg) {
return false
}

publicKey := &ecdsa.PublicKey{Curve: elliptic.P256()}

publicKey.X, publicKey.Y = elliptic.UnmarshalCompressed(elliptic.P256(), pubKey.Key)
if publicKey.X == nil || publicKey.Y == nil {
return false
}

signatureBytes, err := hex.DecodeString(sig.Signature)
if err != nil {
return false
}

authenticatorData, err := hex.DecodeString(sig.AuthenticatorData)
if err != nil {
return false
}

// check authenticatorData length
if len(authenticatorData) < 37 {
return false
}

clientDataHash := sha256.Sum256(clientDataJSON)
payload := append(authenticatorData, clientDataHash[:]...)

h := crypto.SHA256.New()
h.Write(payload)

return ecdsa.VerifyASN1(publicKey, h.Sum(nil), signatureBytes)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider refactoring VerifySignature for better readability.

The VerifySignature method is lengthy and handles multiple steps such as unmarshalling, decoding, and verification processes. Breaking it into smaller helper functions would improve readability and maintainability.

Comment on lines +69 to +72
clientDataJSON, err := hex.DecodeString(sig.ClientDataJSON)
if err != nil {
return false
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Verify that the correct decoding functions are used for ClientDataJSON and AuthenticatorData.

Currently, hex.DecodeString is used to decode sig.ClientDataJSON and sig.AuthenticatorData. Ensure that these fields are actually hex-encoded. Often, these fields are base64 or base64url encoded in authentication protocols like WebAuthn. Using the incorrect decoding method may cause signature verification to fail.

Also applies to: 106-109

Comment on lines +74 to +78
clientData := make(map[string]interface{})
err = json.Unmarshal(clientDataJSON, &clientData)
if err != nil {
return false
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use typed structs instead of map[string]interface{} for JSON unmarshalling.

Employing a typed struct for unmarshalling clientDataJSON can enhance type safety and reduce reliance on type assertions, leading to clearer and more maintainable code.

Comment on lines +99 to +101
WithPubKeyWithValidationFunc(func(pt *authn.AuthnPubKey) error {
return nil
}),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Implement validation logic in WithPubKeyWithValidationFunc

The validation function for authn.AuthnPubKey at lines 99-101 currently returns nil without performing any checks. Implementing validation logic ensures that public keys meet expected criteria and helps detect invalid keys during testing.

Apply this diff to add basic validation:

 WithPubKeyWithValidationFunc(func(pt *authn.AuthnPubKey) error {
-    return nil
+    if pt == nil || len(pt.Key) == 0 {
+        return errors.New("invalid AuthnPubKey: key is nil or empty")
+    }
+    // Additional validation logic can be added here
+    return nil
 }),
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
WithPubKeyWithValidationFunc(func(pt *authn.AuthnPubKey) error {
return nil
}),
WithPubKeyWithValidationFunc(func(pt *authn.AuthnPubKey) error {
if pt == nil || len(pt.Key) == 0 {
return errors.New("invalid AuthnPubKey: key is nil or empty")
}
// Additional validation logic can be added here
return nil
}),

@testinginprod testinginprod added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Sep 27, 2024
@tac0turtle tac0turtle marked this pull request as draft October 1, 2024 07:28
@tac0turtle
Copy link
Member

converting to draft as some changes need to happen before its ready for review. @baryon2 should the sdk team take it over?

@baryon2
Copy link
Author

baryon2 commented Oct 7, 2024

@tac0turtle apologies for the late reply. Yes the sdk team can take over this PR.

@julienrbrt
Copy link
Member

Is there anything left here?

@tac0turtle
Copy link
Member

Is there anything left here?

we need to redo the pr, there may be conflicts with recent changes in accounts as well

@julienrbrt julienrbrt mentioned this pull request Oct 7, 2024
10 tasks
Copy link
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@github-actions github-actions bot added the Stale label Nov 23, 2024
@tac0turtle
Copy link
Member

we should pick this up

@github-actions github-actions bot removed the Stale label Nov 25, 2024
Copy link
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@github-actions github-actions bot added the Stale label Dec 26, 2024
@github-actions github-actions bot closed this Dec 30, 2024
@johnletey
Copy link
Contributor

Any chance this is planned for v0.52, anything we can do to support here?

@tac0turtle
Copy link
Member

ill reopen it, maybe someone can help getting it over the finish line but as it currently stands we wont have capacity for it

@tac0turtle tac0turtle reopened this Dec 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/accounts/base C:x/accounts
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants