Skip to content

Commit

Permalink
support multiple certificates in mtls ca file (#137)
Browse files Browse the repository at this point in the history
* support multiple certificates in mtls ca file

* fix lint error

* fix lint wsl error

* rename variable's name from CA to CAs

* rename variable's name from ca to cas
  • Loading branch information
marcolan018 committed Apr 30, 2021
1 parent cbff1da commit db6ae0c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
7 changes: 5 additions & 2 deletions authentication/mtls.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
// MTLSConfig represents the mTLS configuration for a single tenant.
type MTLSConfig struct {
Tenant string
CA *x509.Certificate
CAs []*x509.Certificate
}

// NewMTLS creates a set of Middlewares for all specified tenants.
Expand All @@ -21,7 +21,10 @@ func NewMTLS(configs []MTLSConfig) map[string]Middleware {
c := c
middlewares[c.Tenant] = func(next http.Handler) http.Handler {
caPool := x509.NewCertPool()
caPool.AddCert(c.CA)

for _, ca := range c.CAs {
caPool.AddCert(ca)
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.TLS.PeerCertificates) == 0 {
Expand Down
38 changes: 24 additions & 14 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func main() {
MTLS *struct {
RawCA []byte `json:"ca"`
CAPath string `json:"caPath"`
ca *x509.Certificate
cas []*x509.Certificate
} `json:"mTLS"`
OPA *struct {
Query string `json:"query"`
Expand Down Expand Up @@ -236,19 +236,29 @@ func main() {
continue
}
}
block, _ := pem.Decode(t.MTLS.RawCA)
if block == nil {
skip.Log("tenant", t.Name, "err", "failed to parse CA certificate PEM")
tenantsCfg.Tenants[i] = nil
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
skip.Log("tenant", t.Name, "err", fmt.Sprintf("failed to parse CA certificate: %v", err))
tenantsCfg.Tenants[i] = nil
continue
var (
block *pem.Block
rest []byte = t.MTLS.RawCA
cert *x509.Certificate
)
for {
block, rest = pem.Decode(rest)
if block == nil {
skip.Log("tenant", t.Name, "err", "failed to parse CA certificate PEM")
tenantsCfg.Tenants[i] = nil
break
}
cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
skip.Log("tenant", t.Name, "err", fmt.Sprintf("failed to parse CA certificate: %v", err))
tenantsCfg.Tenants[i] = nil
break
}
t.MTLS.cas = append(t.MTLS.cas, cert)
if len(rest) == 0 {
break
}
}
t.MTLS.ca = cert
}
if t.OPA != nil {
if t.OPA.URL != "" {
Expand Down Expand Up @@ -423,7 +433,7 @@ func main() {
case t.MTLS != nil:
mTLSs = append(mTLSs, authentication.MTLSConfig{
Tenant: t.Name,
CA: t.MTLS.ca,
CAs: t.MTLS.cas,
})
default:
stdlog.Fatalf("tenant %q must specify either an OIDC or an mTLS configuration", t.Name)
Expand Down

0 comments on commit db6ae0c

Please sign in to comment.