Skip to content

feat(webauthn): session messagepack support #427

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

james-d-elliott
Copy link
Member

@james-d-elliott james-d-elliott commented May 17, 2025

This adds MessagePack support to the SessionData struct. MessagePack allows for serialized storage of data structures similar to JSON but it's faster and more compact. This makes it ideal for storage of session data which is expected to be very fast. It's made to be even faster by the use of the code generator, avoiding the need for runtime reflection in most cases.

This adds MessagePack support to the SessionData struct.
@james-d-elliott james-d-elliott requested a review from a team as a code owner May 17, 2025 06:18
Copy link

coderabbitai bot commented May 17, 2025

Walkthrough

The changes refactor the definitions and serialization logic for CredentialParameter and SessionData structs. These types are moved from their original files into dedicated files, with autogenerated MessagePack serialization methods and comprehensive tests added. The code now uses explicit code generation directives and separates struct definitions from their serialization logic.

Changes

File(s) Change Summary
protocol/options.go, protocol/options_credparam.go Removed CredentialParameter struct from options.go and introduced it in a new file options_credparam.go, including code generation directives and serialization tags.
protocol/options_credparam_gen.go Added autogenerated MessagePack serialization methods for CredentialParameter.
protocol/options_credparam_gen_test.go Added autogenerated tests and benchmarks for CredentialParameter MessagePack serialization.
webauthn/types.go, webauthn/session.go Moved SessionData struct from types.go to new session.go, with code generation directives and serialization tags.
webauthn/session_gen.go Added autogenerated MessagePack serialization methods for SessionData.
webauthn/session_gen_test.go Added autogenerated tests and benchmarks for SessionData MessagePack serialization.

Sequence Diagram(s)

sequenceDiagram
    participant RelyingParty
    participant WebAuthnLib
    participant msgp

    RelyingParty->>WebAuthnLib: Initiate authentication ceremony
    WebAuthnLib->>WebAuthnLib: Create SessionData (with CredentialParameter)
    WebAuthnLib->>msgp: Marshal SessionData to MessagePack
    msgp-->>WebAuthnLib: Serialized data
    WebAuthnLib-->>RelyingParty: Store/return session data
Loading

Poem

In files anew, the structs now dwell,
With MessagePack magic, they serialize well.
Tests and benchmarks hop in with glee,
Each field and byte as neat as can be.
Refactored, reborn, with codegen delight—
A rabbit’s proud hop through a codebase bright!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Copy link

@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: 0

🧹 Nitpick comments (3)
webauthn/session_gen.go (3)

53-60: Potential slice-retention causing unnecessary heap growth

AllowedCredentialIDs is re-sliced in-place when the incoming array is smaller than the previous allocation:

if cap(z.AllowedCredentialIDs) >= int(zb0002) {
    z.AllowedCredentialIDs = (z.AllowedCredentialIDs)[:zb0002]
}

If a very large slice is decoded first and subsequent messages are much smaller, the backing array (and all referenced credential IDs) stay on the heap for the lifetime of SessionData, increasing RSS and GC pressure.

Because this file is generated, a direct edit isn’t ideal, but consider adding the -noresize flag (or similar) in your msgp generation pipeline, or manually post-processing to:

-    z.AllowedCredentialIDs = (z.AllowedCredentialIDs)[:zb0002]
+    if int(float64(cap(z.AllowedCredentialIDs))*0.5) > int(zb0002) {
+        // allocate a fresh slice if we’re dramatically overshooting
+        z.AllowedCredentialIDs = make([][]byte, zb0002)
+    } else {
+        z.AllowedCredentialIDs = (z.AllowedCredentialIDs)[:zb0002]
+    }

This prevents pathological memory retention while still favouring reuse for similar-sized payloads.


88-94: Map clearing retains large backing map

Extensions is cleared with delete in a loop. For messages where Extensions once held many keys but now holds few (or none), the backing map still occupies the old bucket array.

Again, since the file is generated, one workaround is to set z.Extensions = make(map[string]interface{}, zb0004) unconditionally when the decoded size is less than, say, half of len(z.Extensions). That keeps memory proportional to actual usage.

Not critical, but worth noting if SessionData objects are long-lived.


440-449: Minor size-estimate micro-optimisation

Msgsize converts the enum to string for len(string(z.UserVerification)). Repeated allocations could be avoided by caching the conversion once:

- s += 4 + msgp.TimeSize + 3 + msgp.StringPrefixSize + len(string(z.UserVerification))
+ uv := string(z.UserVerification)
+ s += 4 + msgp.TimeSize + 3 + msgp.StringPrefixSize + len(uv)

Negligible for most cases, so feel free to ignore.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 4b43a04 and ece2962.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (8)
  • protocol/options.go (0 hunks)
  • protocol/options_credparam.go (1 hunks)
  • protocol/options_credparam_gen.go (1 hunks)
  • protocol/options_credparam_gen_test.go (1 hunks)
  • webauthn/session.go (1 hunks)
  • webauthn/session_gen.go (1 hunks)
  • webauthn/session_gen_test.go (1 hunks)
  • webauthn/types.go (0 hunks)
💤 Files with no reviewable changes (2)
  • protocol/options.go
  • webauthn/types.go
🧰 Additional context used
🧬 Code Graph Analysis (6)
protocol/options_credparam.go (2)
protocol/options.go (1)
  • CredentialType (83-83)
protocol/webauthncose/webauthncose.go (1)
  • COSEAlgorithmIdentifier (281-281)
webauthn/session_gen_test.go (1)
webauthn/session.go (1)
  • SessionData (15-25)
protocol/options_credparam_gen_test.go (1)
protocol/options_credparam.go (1)
  • CredentialParameter (11-14)
webauthn/session.go (3)
protocol/authenticator.go (1)
  • UserVerificationRequirement (191-191)
protocol/options.go (2)
  • Extensions (255-255)
  • AuthenticationExtensions (94-94)
protocol/options_credparam.go (1)
  • CredentialParameter (11-14)
protocol/options_credparam_gen.go (3)
protocol/options_credparam.go (1)
  • CredentialParameter (11-14)
protocol/options.go (1)
  • CredentialType (83-83)
protocol/webauthncose/webauthncose.go (1)
  • COSEAlgorithmIdentifier (281-281)
webauthn/session_gen.go (4)
webauthn/session.go (1)
  • SessionData (15-25)
protocol/authenticator.go (1)
  • UserVerificationRequirement (191-191)
protocol/options.go (1)
  • Extensions (255-255)
protocol/options_credparam.go (1)
  • CredentialParameter (11-14)
🔇 Additional comments (9)
protocol/options_credparam.go (3)

3-4: Verify import path correctness.
Ensure that the path

import "github.com/go-webauthn/webauthn/protocol/webauthncose"

resolves to the intended package in your module.


5-7: Confirm code generation directives.
The directives

//go:generate msgp
//msgp:replace CredentialType with:string
//msgp:replace webauthncose.COSEAlgorithmIdentifier with:int

correctly instruct msgp to treat CredentialType as string and the COSE algorithm identifier as int.


12-13: Validate struct tags.
The tags

`json:"type" msg:"type"`
`json:"alg" msg:"alg"`

match the JSON and MessagePack keys used throughout the codebase. Confirm they remain consistent with any external consumers of this data.

webauthn/session_gen_test.go (1)

1-124: Skip review of generated test file.
This file is autogenerated by msgp and should not be manually edited.

webauthn/session.go (2)

9-11: Ensure serialization directives correctly match types.
The directives

//msgp:replace protocol.UserVerificationRequirement with:string
//msgp:replace protocol.AuthenticationExtensions with:map[string]any

must align with the underlying definitions in protocol (UserVerificationRequirement is a string alias, and AuthenticationExtensions is a map).


15-25: Review struct field tags and ordering for compatibility.
All fields in SessionData carry both JSON and msg tags:

Challenge string    `json:"challenge" msg:"challenge"`
...
CredParams []protocol.CredentialParameter `json:"credParams,omitempty" msg:"params"`

Verify that key names ("challenge", "rpid", "uid", "allowed", "exp", "uv", "ext", "params") and the use of omitempty maintain backward compatibility with existing session storage and APIs.

protocol/options_credparam_gen_test.go (1)

1-124: Skip review of generated test file.
This file is autogenerated by msgp and should not be manually edited.

protocol/options_credparam_gen.go (1)

1-153: Skip review of generated serialization code.
This file is autogenerated by msgp and should not be manually edited.

webauthn/session_gen.go (1)

3-8: Autogenerated file – generally LGTM

The file is clearly generated by msgp and adheres to the expected encoding/decoding contract for SessionData. No functional issues observed in the generated code itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant