-
Notifications
You must be signed in to change notification settings - Fork 53
/
oidc.go
180 lines (149 loc) · 4.59 KB
/
oidc.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"crypto/rsa"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
const jwksUriPath = "/jwks"
const certsUriPath = "/certs"
var OpenIDConfig struct {
IssuerURL string
KeyID string
PrivateKey *rsa.PrivateKey
}
type OpenIDConnectClaims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
jwt.StandardClaims
}
func init() {
var err error
openIdPrivateKeyStr2, err := ioutil.ReadFile("oidc.key")
if err != nil {
panic(err)
}
OpenIDConfig.PrivateKey, err = jwt.ParseRSAPrivateKeyFromPEM([]byte(openIdPrivateKeyStr2))
if err != nil {
panic(err)
}
OpenIDConfig.IssuerURL = "http://cloud-tasks-emulator"
OpenIDConfig.KeyID = "cloudtasks-emulator-test"
}
func createOIDCToken(serviceAccountEmail string, handlerUrl string, audience string) string {
if audience == "" {
audience = handlerUrl
}
now := time.Now()
claims := OpenIDConnectClaims{
Email: serviceAccountEmail,
EmailVerified: true,
StandardClaims: jwt.StandardClaims{
Subject: serviceAccountEmail,
Audience: audience,
Issuer: OpenIDConfig.IssuerURL,
IssuedAt: now.Unix(),
NotBefore: now.Unix(),
ExpiresAt: now.Add(5 * time.Minute).Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
token.Header["kid"] = OpenIDConfig.KeyID
tokenString, err := token.SignedString(OpenIDConfig.PrivateKey)
if err != nil {
log.Fatalf("Failed to create OIDC token: %v", err)
}
return tokenString
}
func openIDConfigHttpHandler(w http.ResponseWriter, r *http.Request) {
config := map[string]interface{}{
"issuer": OpenIDConfig.IssuerURL,
"jwks_uri": OpenIDConfig.IssuerURL + jwksUriPath,
"id_token_signing_alg_values_supported": []string{"RS256"},
"claims_supported": []string{"aud", "email", "email_verified", "exp", "iat", "iss", "nbf"},
}
respondJSON(w, config, 24*time.Hour)
}
func respondJSON(w http.ResponseWriter, body interface{}, expiresAfter time.Duration) {
json, err := json.Marshal(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
utc, _ := time.LoadLocation("UTC")
expires := time.Now().In(utc).Add(expiresAfter).Format(http.TimeFormat)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "public")
w.Header().Set("Expires", expires)
w.Write(json)
}
func openIDJWKSHttpHandler(w http.ResponseWriter, r *http.Request) {
publicKey := OpenIDConfig.PrivateKey.Public().(*rsa.PublicKey)
b64Url := base64.URLEncoding.WithPadding(base64.NoPadding)
config := map[string]interface{}{
"keys": []map[string]string{
{
// Ideally we would export the exponent from the key too but frankly
// it's always AQAB in practice and I lost the will to live trying to
// base64url encode a 2-bytes int in go!
"e": "AQAB",
"n": b64Url.EncodeToString(publicKey.N.Bytes()),
"kid": OpenIDConfig.KeyID,
"use": "sig",
"alg": "RSA256",
"kty": "RSA",
},
},
}
respondJSON(w, config, 24*time.Hour)
}
func openIDCertsHttpHandler(w http.ResponseWriter, r *http.Request) {
var err error
openIdcert, err := ioutil.ReadFile("oidc.cert")
if err != nil {
panic(err)
}
config := map[string]interface{}{
OpenIDConfig.KeyID: string(openIdcert),
}
respondJSON(w, config, 24*time.Hour)
}
func serveOpenIDConfigurationEndpoint(listenAddr string, listenPort string) *http.Server {
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", openIDConfigHttpHandler)
mux.HandleFunc(jwksUriPath, openIDJWKSHttpHandler)
mux.HandleFunc(certsUriPath, openIDCertsHttpHandler)
server := &http.Server{Addr: listenAddr + ":" + listenPort, Handler: mux}
go server.ListenAndServe()
return server
}
func configureOpenIdIssuer(issuerUrl string) (*http.Server, error) {
url, err := url.ParseRequestURI(issuerUrl)
if err != nil {
return nil, fmt.Errorf("-openid-issuer must be a base URL e.g. http://any-host:8237")
}
if url.Scheme != "http" {
return nil, fmt.Errorf("-openid-issuer only supports http protocol")
}
if url.Path != "" {
return nil, fmt.Errorf("-openid-issuer must not contain a path")
}
OpenIDConfig.IssuerURL = issuerUrl
hostParts := strings.Split(url.Host, ":")
var port string
if len(hostParts) > 1 {
port = hostParts[1]
} else {
port = "80"
}
listenAddr := "0.0.0.0"
fmt.Printf("Issuing OpenID tokens as %v - running endpoint on %v:%v\n", issuerUrl, listenAddr, port)
return serveOpenIDConfigurationEndpoint(listenAddr, port), nil
}