/
auth.go
62 lines (54 loc) · 1.8 KB
/
auth.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
54
55
56
57
58
59
60
61
62
//go:build !no_logs
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package kubernetes
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
)
// Kubernetes constants
const (
DefaultServiceAccountPath = "/var/run/secrets/kubernetes.io/serviceaccount"
DefaultServiceAccountTokenPath = DefaultServiceAccountPath + "/token"
DefaultServiceAccountCAPath = DefaultServiceAccountPath + "/ca.crt"
)
// IsServiceAccountTokenAvailable returns if a service account token is available on disk
func IsServiceAccountTokenAvailable() bool {
_, err := os.Stat(DefaultServiceAccountPath)
return err == nil
}
// GetBearerToken reads the serviceaccount token
func GetBearerToken(authTokenPath string) (string, error) {
token, err := ioutil.ReadFile(authTokenPath)
if err != nil {
return "", fmt.Errorf("could not read token from %s: %s", authTokenPath, err)
}
return string(token), nil
}
// GetCertificates loads the certificate and the private key
func GetCertificates(certFilePath, keyFilePath string) ([]tls.Certificate, error) {
var certs []tls.Certificate
cert, err := tls.LoadX509KeyPair(certFilePath, keyFilePath)
if err != nil {
return certs, err
}
return append(certs, cert), nil
}
// GetCertificateAuthority loads the issuing certificate authority
func GetCertificateAuthority(certPath string) (*x509.CertPool, error) {
caCert, err := ioutil.ReadFile(certPath)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(caCert)
if ok == false {
return caCertPool, fmt.Errorf("fail to load certificate authority: %s", certPath)
}
return caCertPool, nil
}