summaryrefslogtreecommitdiffstats
path: root/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/tls/AthenzX509CertificateUtils.java
blob: bec21a5b25f54accd971e2d64f5fb361e25fe98f (plain) (blame)
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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.tls;

import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzRole;
import com.yahoo.vespa.athenz.utils.AthenzIdentities;

import java.security.cert.X509Certificate;
import java.util.List;

import static com.yahoo.security.SubjectAlternativeName.Type.RFC822_NAME;

/**
 * Utility methods for Athenz issued x509 certificates
 *
 * @author bjorncs
 */
public class AthenzX509CertificateUtils {

    private AthenzX509CertificateUtils() {}

    public static AthenzIdentity getIdentityFromRoleCertificate(X509Certificate certificate) {
        List<com.yahoo.security.SubjectAlternativeName> sans = com.yahoo.security.X509CertificateUtils.getSubjectAlternativeNames(certificate);
        return sans.stream()
                .filter(san -> san.getType() == RFC822_NAME)
                .map(com.yahoo.security.SubjectAlternativeName::getValue)
                .map(AthenzX509CertificateUtils::getIdentityFromSanEmail)
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Could not find identity in SAN: " + sans));
    }

    public static AthenzRole getRolesFromRoleCertificate(X509Certificate certificate) {
        String commonName = com.yahoo.security.X509CertificateUtils.getSubjectCommonNames(certificate).get(0);
        return AthenzRole.fromResourceNameString(commonName);
    }

    private static AthenzIdentity getIdentityFromSanEmail(String email) {
        int separator = email.indexOf('@');
        if (separator == -1) throw new IllegalArgumentException("Invalid SAN email: " + email);
        return AthenzIdentities.from(email.substring(0, separator));
    }

}