-
Notifications
You must be signed in to change notification settings - Fork 283
/
principal.go
53 lines (40 loc) · 1.51 KB
/
principal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2018 Oath, Inc.
// Licensed under the terms of the Apache version 2.0 license. See LICENSE file for terms.
package athenzutils
import (
"crypto/x509"
"fmt"
"strings"
)
// ExtractServicePrincipal returns the Athenz Service principal for the given
// certificate which could be either a service certificate or a role certificate.
// If the certificate does not have the Athenz expected name format
// the method will an appropriate error.
func ExtractServicePrincipal(x509Cert x509.Certificate) (string, error) {
// let's first get the common name of the certificate
principal := x509Cert.Subject.CommonName
if principal == "" {
return "", fmt.Errorf("certificate does not have a common name")
}
// check to see if we're dealing with role certificate which
// has the <domain>:role.<rolename> format or service
// certificate which has the <domain>.<service> format
if strings.Contains(principal, ":role.") {
// it's a role certificate so we're going to extract
// our service principal from the SAN email fieid
// verify that we must have only a single email
// field in the certificate
emails := x509Cert.EmailAddresses
if len(emails) != 1 {
return "", fmt.Errorf("certificate does not have a single email SAN value")
}
// athenz always verifies that we include a valid
// email in the certificate
idx := strings.Index(emails[0], "@")
if idx == -1 {
return "", fmt.Errorf("certificate email is invalid: %s", emails[0])
}
principal = emails[0][0:idx]
}
return principal, nil
}