diff options
author | tjpcc <tjp@ctrl-c.club> | 2023-01-20 10:58:35 -0700 |
---|---|---|
committer | tjpcc <tjp@ctrl-c.club> | 2023-01-20 10:58:35 -0700 |
commit | 8229f31f70ecdbe03d03c96cba17d6ee85397bca (patch) | |
tree | 5c51a1bdd9366a69fd1cf03dcdd1c41e49bcb6e2 /contrib/tlsauth/approver_test.go | |
parent | a1c186878d228bada894a6fd580bfc4eb9da2ffa (diff) |
"tlsauth" contrib package
This package adds authentication middlewares via TLS client
certificates.
Diffstat (limited to 'contrib/tlsauth/approver_test.go')
-rw-r--r-- | contrib/tlsauth/approver_test.go | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/contrib/tlsauth/approver_test.go b/contrib/tlsauth/approver_test.go new file mode 100644 index 0000000..a2af838 --- /dev/null +++ b/contrib/tlsauth/approver_test.go @@ -0,0 +1,47 @@ +package tlsauth_test + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + + "tildegit.org/tjp/gus/contrib/tlsauth" +) + +func TestRequireSpecificIdentity(t *testing.T) { + cert1, err := leafCert("testdata/client1.crt", "testdata/client1.key") + assert.Nil(t, err) + + cert2, err := leafCert("testdata/client2.crt", "testdata/client2.key") + assert.Nil(t, err) + + assert.True(t, cert1.Equal(cert1)) + assert.False(t, cert1.Equal(cert2)) + assert.False(t, cert2.Equal(cert1)) + assert.True(t, cert2.Equal(cert2)) + + assert.True(t, tlsauth.RequireSpecificIdentity(cert1)(cert1)) + assert.False(t, tlsauth.RequireSpecificIdentity(cert1)(cert2)) + assert.False(t, tlsauth.RequireSpecificIdentity(cert2)(cert1)) + assert.True(t, tlsauth.RequireSpecificIdentity(cert2)(cert2)) +} + +func leafCert(certfile, keyfile string) (*x509.Certificate, error) { + cert, err := tls.LoadX509KeyPair(certfile, keyfile) + if err != nil { + return nil, err + } + + if cert.Leaf != nil { + return cert.Leaf, nil + } + + if len(cert.Certificate) == 0 { + return nil, errors.New("no certificate blocks found") + } + + return x509.ParseCertificate(cert.Certificate[0]) +} |