-
Notifications
You must be signed in to change notification settings - Fork 1
feat(pkg): shared identity and certauth for session mTLS #337
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| // Package certauth provides shared certificate signing request helpers for | ||
| // session-bound mTLS credentials issued by the platform API and adapter CLI. | ||
| package certauth | ||
|
|
||
| import ( | ||
| "crypto/ecdsa" | ||
| "crypto/elliptic" | ||
| "crypto/rand" | ||
| "crypto/x509" | ||
| "encoding/pem" | ||
| "fmt" | ||
| "net/url" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "mcp-runtime/pkg/identity" | ||
| ) | ||
|
|
||
| // BuildSessionCSR generates a fresh P-256 key and a CSR whose only SAN is the | ||
| // session SPIFFE URI. It returns PKCS#8 key PEM, CSR PEM, and the SPIFFE ID string. | ||
| func BuildSessionCSR(trustDomain, namespace, sessionName string) (keyPEM, csrPEM []byte, spiffeID string, err error) { | ||
| trustDomain = strings.TrimSpace(trustDomain) | ||
| if trustDomain == "" { | ||
| return nil, nil, "", fmt.Errorf("trust domain must not be empty") | ||
| } | ||
| spiffeID = identity.SessionSPIFFEID(trustDomain, namespace, sessionName) | ||
| spiffe, err := url.Parse(spiffeID) | ||
| if err != nil { | ||
| return nil, nil, "", fmt.Errorf("parse session SPIFFE URI: %w", err) | ||
| } | ||
| key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | ||
| if err != nil { | ||
| return nil, nil, "", fmt.Errorf("generate client key: %w", err) | ||
| } | ||
| csrDER, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{ | ||
| URIs: []*url.URL{spiffe}, | ||
| }, key) | ||
| if err != nil { | ||
| return nil, nil, "", fmt.Errorf("create CSR: %w", err) | ||
| } | ||
| keyDER, err := x509.MarshalPKCS8PrivateKey(key) | ||
| if err != nil { | ||
| return nil, nil, "", fmt.Errorf("marshal client key: %w", err) | ||
| } | ||
| keyPEM = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) | ||
| csrPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}) | ||
| return keyPEM, csrPEM, spiffeID, nil | ||
| } | ||
|
|
||
| // ValidateCSRPEM parses and validates a PEM CSR. The CSR must be signed, carry | ||
| // exactly one URI SAN equal to expectedSPIFFEID, and must not include DNS, | ||
| // email, or IP subject alternative names. It returns the CSR DER on success. | ||
| func ValidateCSRPEM(raw, expectedSPIFFEID string) ([]byte, error) { | ||
| block, _ := pem.Decode([]byte(raw)) | ||
| if block == nil || block.Type != "CERTIFICATE REQUEST" { | ||
| return nil, fmt.Errorf("csr must be a PEM CERTIFICATE REQUEST") | ||
| } | ||
| csr, err := x509.ParseCertificateRequest(block.Bytes) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("parse csr: %w", err) | ||
| } | ||
| if err := csr.CheckSignature(); err != nil { | ||
| return nil, fmt.Errorf("csr signature verification failed: %w", err) | ||
| } | ||
| if len(csr.URIs) != 1 || csr.URIs[0].String() != expectedSPIFFEID { | ||
| return nil, fmt.Errorf("csr must contain exactly the SPIFFE URI %q", expectedSPIFFEID) | ||
| } | ||
| if len(csr.DNSNames) != 0 || len(csr.EmailAddresses) != 0 || len(csr.IPAddresses) != 0 { | ||
| return nil, fmt.Errorf("csr may not contain DNS, email, or IP subject alternative names") | ||
| } | ||
| return block.Bytes, nil | ||
| } | ||
|
|
||
| // WritePrivateFile writes data to dir/name with mode, rejecting path traversal. | ||
| func WritePrivateFile(dir, name string, data []byte, mode os.FileMode) error { | ||
| root, err := os.OpenRoot(dir) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer root.Close() | ||
| file, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if err := file.Chmod(mode); err != nil { | ||
| _ = file.Close() | ||
| return err | ||
| } | ||
| if _, err := file.Write(data); err != nil { | ||
| _ = file.Close() | ||
| return err | ||
| } | ||
| return file.Close() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| package certauth | ||
|
|
||
| import ( | ||
| "crypto/ecdsa" | ||
| "crypto/elliptic" | ||
| "crypto/rand" | ||
| "crypto/x509" | ||
| "encoding/pem" | ||
| "net/url" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestBuildSessionCSR(t *testing.T) { | ||
| t.Parallel() | ||
| keyPEM, csrPEM, spiffeID, err := BuildSessionCSR("mcpruntime.org", "mcp-team-acme", "adapter-xyz") | ||
| if err != nil { | ||
| t.Fatalf("BuildSessionCSR: %v", err) | ||
| } | ||
| want := "spiffe://mcpruntime.org/ns/mcp-team-acme/session/adapter-xyz" | ||
| if spiffeID != want { | ||
| t.Fatalf("spiffeID = %q, want %q", spiffeID, want) | ||
| } | ||
| if _, err := ValidateCSRPEM(string(csrPEM), want); err != nil { | ||
| t.Fatalf("ValidateCSRPEM() error = %v", err) | ||
| } | ||
| if block, _ := pem.Decode(keyPEM); block == nil || block.Type != "PRIVATE KEY" { | ||
| t.Fatal("key PEM is not a PRIVATE KEY block") | ||
| } | ||
| } | ||
|
|
||
| func TestValidateCSRPEM(t *testing.T) { | ||
| t.Parallel() | ||
| const expected = "spiffe://example.org/ns/team-a/session/session-1" | ||
| _, csrPEM, _, err := BuildSessionCSR("example.org", "team-a", "session-1") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if _, err := ValidateCSRPEM(string(csrPEM), expected); err != nil { | ||
| t.Fatalf("ValidateCSRPEM() error = %v", err) | ||
| } | ||
| if _, err := ValidateCSRPEM(string(csrPEM), strings.Replace(expected, "session-1", "session-2", 1)); err == nil { | ||
| t.Fatal("ValidateCSRPEM() accepted a CSR for another session") | ||
| } | ||
| } | ||
|
|
||
| func TestValidateCSRPEMRejectsAdditionalSANs(t *testing.T) { | ||
| t.Parallel() | ||
| const expected = "spiffe://example.org/ns/team-a/session/session-1" | ||
| key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| uri, err := url.Parse(expected) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| csrDER, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{ | ||
| URIs: []*url.URL{uri}, | ||
| DNSNames: []string{"attacker.example"}, | ||
| }, key) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| csrPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}) | ||
| if _, err := ValidateCSRPEM(string(csrPEM), expected); err == nil { | ||
| t.Fatal("ValidateCSRPEM() accepted an additional DNS SAN") | ||
| } | ||
| } | ||
|
|
||
| func TestWritePrivateFileRejectsTraversal(t *testing.T) { | ||
| t.Parallel() | ||
| dir := t.TempDir() | ||
| if err := WritePrivateFile(dir, "client.key", []byte("secret"), 0o600); err != nil { | ||
| t.Fatalf("WritePrivateFile() error = %v", err) | ||
| } | ||
| if err := WritePrivateFile(dir, "../escape", []byte("nope"), 0o600); err == nil { | ||
| t.Fatal("WritePrivateFile() allowed path traversal") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| package identity | ||
|
|
||
| import ( | ||
| "crypto/x509" | ||
| "strings" | ||
| ) | ||
|
|
||
| // CertificateHasURI reports whether cert carries want as a URI SAN. | ||
| func CertificateHasURI(cert *x509.Certificate, want string) bool { | ||
| if cert == nil { | ||
| return false | ||
| } | ||
| for _, uri := range cert.URIs { | ||
| if uri != nil && uri.String() == want { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // FirstClientSPIFFEURI returns the first spiffe:// URI SAN on cert whose trust | ||
| // domain matches trustDomain when trustDomain is non-empty. Returns "" when no | ||
| // matching URI is present. | ||
| func FirstClientSPIFFEURI(cert *x509.Certificate, trustDomain string) string { | ||
| if cert == nil { | ||
| return "" | ||
| } | ||
| trustDomain = strings.TrimSpace(trustDomain) | ||
| for _, uri := range cert.URIs { | ||
| if uri == nil || !strings.EqualFold(uri.Scheme, "spiffe") { | ||
| continue | ||
| } | ||
| if trustDomain != "" && !strings.EqualFold(uri.Host, trustDomain) { | ||
| continue | ||
| } | ||
| return uri.String() | ||
| } | ||
| return "" | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Separating the CSR parsing and signature verification checks improves readability and preserves the underlying error details, which is highly beneficial for debugging.