Repository: go-webauthn/webauthn
Pull request #358 (2024-12-22 12:53:27)

refactor(protocol): adjust formatting
This addresses formatting styles from the previous commit.

coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> <details>
> <summary>📥 Commits</summary>
> 
> Reviewing files that changed from the base of the PR and between 339114cc55df3e0cdd71e6ed0c093fe2aa331a09 and 2df9bdbc25d4ad94dc393d20305dbfc7940bdec6.
> 
> </details>
> 
> <details>
> <summary>📒 Files selected for processing (3)</summary>
> 
> * `metadata/metadata.go` (1 hunks)
> * `protocol/attestation.go` (1 hunks)
> * `protocol/attestation_tpm.go` (1 hunks)
> 
> </details>
> 
> ```ascii
>  ________________________
> < Code review is my jam. >
>  ------------------------
>   \
>    \   (\__/)
>        (•ㅅ•)
>        / 　 づ
> ```

<!-- end of auto-generated comment: review in progress by coderabbit.ai -->

<!-- tips_start -->

---

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?

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai):

- 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 generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR. ([Beta](https://docs.coderabbit.ai/early-access#beta))
- `@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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

Patch:
diff --git a/metadata/metadata.go b/metadata/metadata.go
index 0a43e68..d6e9183 100644
--- a/metadata/metadata.go
+++ b/metadata/metadata.go
@@ -319,15 +319,26 @@ type Statement struct {
 	AuthenticatorGetInfo AuthenticatorGetInfo
 }
 
-func (s *Statement) Verifier() (opts x509.VerifyOptions) {
+func (s *Statement) Verifier(x5cis []*x509.Certificate) (opts x509.VerifyOptions) {
 	roots := x509.NewCertPool()
 
 	for _, root := range s.AttestationRootCertificates {
 		roots.AddCert(root)
 	}
 
+	var intermediates *x509.CertPool
+
+	if len(x5cis) > 0 {
+		intermediates = x509.NewCertPool()
+
+		for _, x5c := range x5cis {
+			intermediates.AddCert(x5c)
+		}
+	}
+
 	return x509.VerifyOptions{
-		Roots: roots,
+		Roots:         roots,
+		Intermediates: intermediates,
 	}
 }
 


Test patch:
diff --git a/protocol/attestation.go b/protocol/attestation.go
index 72a64f0..be30e92 100644
--- a/protocol/attestation.go
+++ b/protocol/attestation.go
@@ -232,8 +232,10 @@ func (a *AttestationObject) VerifyAttestation(clientDataHash []byte, mds metadat
 		}
 
 		var (
-			x5c     *x509.Certificate
-			parents []*x509.Certificate
+			x5c, parsed *x509.Certificate
+			x5cis       []*x509.Certificate
+			raw         []byte
+			ok          bool
 		)
 
 		if len(x5cs) == 0 {
@@ -241,18 +243,18 @@ func (a *AttestationObject) VerifyAttestation(clientDataHash []byte, mds metadat
 		}
 
 		for _, x5cAny := range x5cs {
-			x5cRaw, ok := x5cAny.([]byte)
-			if !ok {
+			if raw, ok = x5cAny.([]byte); !ok {
 				return ErrInvalidAttestation.WithDetails("Unable to parse attestation certificate from x5c during attestation validation").WithInfo(fmt.Sprintf("The first certificate in the attestation was type '%T' but '[]byte' was expected", x5cs[0]))
 			}
-			x5cParsed, err := x509.ParseCertificate(x5cRaw)
-			if err != nil {
+
+			if parsed, err = x509.ParseCertificate(raw); err != nil {
 				return ErrInvalidAttestation.WithDetails("Unable to parse attestation certificate from x5c during attestation validation").WithInfo(fmt.Sprintf("Error returned from x509.ParseCertificate: %+v", err))
 			}
+
 			if x5c == nil {
-				x5c = x5cParsed
+				x5c = parsed
 			} else {
-				parents = append(parents, x5cParsed)
+				x5cis = append(x5cis, parsed)
 			}
 		}
 
@@ -260,27 +262,25 @@ func (a *AttestationObject) VerifyAttestation(clientDataHash []byte, mds metadat
 			if err = tpmParseSANExtension(x5c); err != nil {
 				return err
 			}
+
 			if err = tpmRemoveEKU(x5c); err != nil {
 				return err
 			}
-			for _, parent := range parents {
+
+			for _, parent := range x5cis {
 				if err = tpmRemoveEKU(parent); err != nil {
 					return err
 				}
 			}
 		}
 
-		if x5c.Subject.CommonName != x5c.Issuer.CommonName {
+		if x5c != nil && x5c.Subject.CommonName != x5c.Issuer.CommonName {
 			if !entry.MetadataStatement.AttestationTypes.HasBasicFull() {
 				return ErrInvalidAttestation.WithDetails("Unable to validate attestation statement signature during attestation validation: attestation with full attestation from authenticator that does not support full attestation")
 			}
-			verifier := entry.MetadataStatement.Verifier()
-			if len(parents) != 0 {
-				verifier.Intermediates = x509.NewCertPool()
-				for _, parent := range parents {
-					verifier.Intermediates.AddCert(parent)
-				}
-			}
+
+			verifier := entry.MetadataStatement.Verifier(x5cis)
+
 			if _, err = x5c.Verify(verifier); err != nil {
 				return ErrInvalidAttestation.WithDetails(fmt.Sprintf("Unable to validate attestation signature statement during attestation validation: invalid certificate chain from MDS: %v", err))
 			}
diff --git a/protocol/attestation_tpm.go b/protocol/attestation_tpm.go
index 9251ae3..873e864 100644
--- a/protocol/attestation_tpm.go
+++ b/protocol/attestation_tpm.go
@@ -395,10 +395,7 @@ var (
 	oidExtensionSubjectAltName   = []int{2, 5, 29, 17}
 	oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
 	oidExtensionBasicConstraints = []int{2, 5, 29, 19}
-
-	// From wincrypt.h of Windows SDK.
-	// Enhanced Key Usage for Privacy CA encryption certificate
-	oidKpPrivacyCA = []int{1, 3, 6, 1, 4, 1, 311, 21, 36}
+	oidKpPrivacyCA               = []int{1, 3, 6, 1, 4, 1, 311, 21, 36}
 )
 
 type tpmBasicConstraints struct {
@@ -406,24 +403,32 @@ type tpmBasicConstraints struct {
 	MaxPathLen int  `asn1:"optional,default:-1"`
 }
 
-// remove extension key usage to avoid ExtKeyUsage check failure
-// see also https://github.com/go-webauthn/webauthn/issues/342
+// Remove extension key usage to avoid ExtKeyUsage check failure.
 func tpmRemoveEKU(x5c *x509.Certificate) error {
-	var unknown []asn1.ObjectIdentifier
-	hasAiK := false
+	var (
+		unknown []asn1.ObjectIdentifier
+		hasAiK  bool
+	)
+
 	for _, eku := range x5c.UnknownExtKeyUsage {
 		if eku.Equal(tcgKpAIKCertificate) {
 			hasAiK = true
+
 			continue
 		}
+
 		if eku.Equal(oidKpPrivacyCA) {
 			continue
 		}
+
 		unknown = append(unknown, eku)
 	}
+
 	if !hasAiK {
 		return ErrAttestationFormat.WithDetails("AIK certificate missing EKU")
 	}
+
 	x5c.UnknownExtKeyUsage = unknown
+
 	return nil
 }