|
| 1 | +// Copyright 2018 Oath, Inc. |
| 2 | +// Licensed under the terms of the Apache version 2.0 license. See LICENSE file for terms. |
| 3 | + |
| 4 | +package athenzutils |
| 5 | + |
| 6 | +import ( |
| 7 | + "crypto/x509" |
| 8 | + "encoding/pem" |
| 9 | + "io/ioutil" |
| 10 | + "testing" |
| 11 | +) |
| 12 | + |
| 13 | +func TestExtractServicePrincipal(test *testing.T) { |
| 14 | + |
| 15 | + x509Cert, _ := getCertFromFile("data/service_identity1.cert") |
| 16 | + principal, _ := ExtractServicePrincipal(*x509Cert) |
| 17 | + if principal != "athenz.production" { |
| 18 | + test.Errorf("invalid principal %s from data/service_identity1.cert", principal) |
| 19 | + } |
| 20 | + |
| 21 | + x509Cert, _ = getCertFromFile("data/service_identity2.cert") |
| 22 | + principal, _ = ExtractServicePrincipal(*x509Cert) |
| 23 | + if principal != "athenz.syncer" { |
| 24 | + test.Errorf("invalid principal %s from data/service_identity2.cert", principal) |
| 25 | + } |
| 26 | + |
| 27 | + x509Cert, _ = getCertFromFile("data/valid_email_x509.cert") |
| 28 | + principal, _ = ExtractServicePrincipal(*x509Cert) |
| 29 | + if principal != "athens.zts" { |
| 30 | + test.Errorf("invalid principal %s from data/valid_email.cert", principal) |
| 31 | + } |
| 32 | + |
| 33 | + x509Cert, _ = getCertFromFile("data/no_cn_x509.cert") |
| 34 | + principal, err := ExtractServicePrincipal(*x509Cert) |
| 35 | + if err == nil { |
| 36 | + test.Errorf("no error from invalid file data/no_cn_x509.cert: %s", principal) |
| 37 | + } |
| 38 | + |
| 39 | + x509Cert, _ = getCertFromFile("data/invalid_email_x509.cert") |
| 40 | + principal, err = ExtractServicePrincipal(*x509Cert) |
| 41 | + if err == nil { |
| 42 | + test.Errorf("no error from invalid file data/invalid_email_x509.cert: %s", principal) |
| 43 | + } |
| 44 | + |
| 45 | + x509Cert, _ = getCertFromFile("data/multiple_email_x509.cert") |
| 46 | + principal, err = ExtractServicePrincipal(*x509Cert) |
| 47 | + if err == nil { |
| 48 | + test.Errorf("no error from invalid file data/multiple_email_x509.cert: %s", principal) |
| 49 | + } |
| 50 | + |
| 51 | + x509Cert, _ = getCertFromFile("data/no_email_x509.cert") |
| 52 | + principal, err = ExtractServicePrincipal(*x509Cert) |
| 53 | + if err == nil { |
| 54 | + test.Errorf("no error from invalid file data/no_email_x509.cert: %s", principal) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +func getCertFromFile(certFile string) (*x509.Certificate, error) { |
| 59 | + data, err := ioutil.ReadFile(certFile) |
| 60 | + if err != nil { |
| 61 | + return nil, err |
| 62 | + } |
| 63 | + var block *pem.Block |
| 64 | + block, _ = pem.Decode(data) |
| 65 | + return x509.ParseCertificate(block.Bytes) |
| 66 | +} |
0 commit comments