File: github_actions_test.go

package info (click to toggle)
golang-github-openpubkey-openpubkey 0.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 964 kB
  • sloc: makefile: 10
file content (257 lines) | stat: -rw-r--r-- 9,124 bytes parent folder | download
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright 2024 OpenPubkey
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package providers

import (
	"context"
	"crypto/rand"
	"crypto/rsa"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/lestrrat-go/jwx/v2/jwa"
	"github.com/lestrrat-go/jwx/v2/jws"
	"github.com/openpubkey/openpubkey/discover"
	"github.com/openpubkey/openpubkey/gq"
	"github.com/openpubkey/openpubkey/providers/mocks"
	"github.com/openpubkey/openpubkey/util"
	"github.com/stretchr/testify/require"
)

func TestGithubOpTableTest(t *testing.T) {
	issuer := githubIssuer
	providerOverride, err := mocks.NewMockProviderBackend(issuer, "RS256", 2)
	require.NoError(t, err)

	op := &GithubOp{
		issuer:                    githubIssuer,
		rawTokenRequestURL:        "fakeTokenURL",
		tokenRequestAuthToken:     "fakeToken",
		publicKeyFinder:           providerOverride.PublicKeyFinder,
		requestTokensOverrideFunc: providerOverride.RequestTokensOverrideFunc,
	}

	cic := GenCIC(t)
	expSigningKey, expKeyID, expRecord := providerOverride.RandomSigningKey()
	idTokenTemplate := mocks.IDTokenTemplate{
		CommitFunc:  mocks.AddAudCommit,
		Issuer:      issuer,
		Nonce:       "empty",
		NoNonce:     false,
		Aud:         "empty",
		KeyID:       expKeyID,
		NoKeyID:     false,
		Alg:         expRecord.Alg,
		NoAlg:       false,
		ExtraClaims: map[string]any{"sha": "c7d5b5ff9b2130a53526dcc44a1f69ef0e50d003"},
		SigningKey:  expSigningKey,
	}
	providerOverride.SetIDTokenTemplate(&idTokenTemplate)

	tokens, err := op.RequestTokens(context.Background(), cic)
	require.NoError(t, err)
	idToken := tokens.IDToken
	require.NotNil(t, idToken)

	_, payloadB64, _, err := jws.SplitCompact(idToken)
	require.NoError(t, err)

	headers := extractHeaders(t, idToken)
	require.Equal(t, gq.GQ256, headers.Algorithm(), "github must only return GQ signed ID Tokens but we got (%s)", headers.Algorithm())

	origHeadersB64, err := gq.OriginalJWTHeaders(idToken)
	require.NoError(t, err)
	origHeaders, err := util.Base64DecodeForJWT(origHeadersB64)
	require.NoError(t, err)
	require.Contains(t, string(origHeaders), "RS256")

	payload, err := util.Base64DecodeForJWT(payloadB64)
	require.NoError(t, err)

	payloadClaims := struct {
		Issuer   string `json:"iss"`
		Subject  string `json:"sub"`
		Audience string `json:"aud"`
		Nonce    string `json:"nonce,omitempty"`
	}{}
	err = json.Unmarshal(payload, &payloadClaims)
	require.NoError(t, err)
	pkRecord, err := op.PublicKeyByToken(context.Background(), idToken)
	require.NoError(t, err)

	// Check that GQ Signature verifies
	rsaKey, ok := pkRecord.PublicKey.(*rsa.PublicKey)

	require.True(t, ok)
	ok, err = gq.GQ256VerifyJWT(rsaKey, idToken)
	require.NoError(t, err)
	require.True(t, ok)
}

// These two tests are regression tests for  deserialization bug
// that broke our ability to read the ID Token directly from the HTTP
// response. To ensure we don't break this again this test stands up a server
// so that all of the RequestToken code is tested. For all the other tests
// we just use the standard override functions.
func TestGithubOpSimpleRequest(t *testing.T) {
	expCicHash := "LJJfahE5cC1AgAWrMkUDL85d0oSSBcP6FJVSulzojds"

	// Setup expected test data
	expProtected := []byte(`{"alg":"RS256","kid":"1F2AB83404C08EC9EA0BB99DAED02186B091DBF4","typ":"JWT","x5t":"Hyq4NATAjsnqC7mdrtAhhrCR2_Q"}`)
	expPayload := []byte(`{"sub":"repo:example/fake:ref:refs/heads/main","aud":"LJJfahE5cC1AgAWrMkUDL85d0oSSBcP6FJVSulzojds","ref":"refs/heads/main","sha":\"353722c917a3f94988b826b82405ca05feddb1fe","repository":"example/fake","repository_owner":"fakeowner","iss":"https://token.actions.githubusercontent.com","nbf":1709839869,"exp":1709840769,"iat":1709840469}`)
	expSig := []byte(`fakesig`)
	expIdToken := string(util.Base64EncodeForJWT(expProtected)) + "." + string(util.Base64EncodeForJWT(expPayload)) + "." + string(util.Base64EncodeForJWT(expSig))
	expResponseBody := fmt.Sprintf(`{"count":1857,"value":"%s"}`, expIdToken)

	testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		res.WriteHeader(http.StatusOK)
		_, err := res.Write([]byte(expResponseBody))
		require.NoError(t, err)
	}))
	defer func() { testServer.Close() }()

	tokenRequestURL := testServer.URL
	authToken := "fakeAuthToken"
	op := NewGithubOp(tokenRequestURL, authToken)

	// Lowercase requestTokens just gets the ID Token (no GQ signing or modification)
	idTokenLB, err := op.requestTokens(context.TODO(), expCicHash)
	require.NoError(t, err)
	require.NotNil(t, idTokenLB)

	idToken := make([]byte, len(idTokenLB.Bytes()))
	copy(idToken, idTokenLB.Bytes())

	headerB64, payloadB64, sigB64, err := jws.SplitCompact(idToken)
	require.NoError(t, err)

	header, err := util.Base64DecodeForJWT(headerB64)
	require.NoError(t, err)
	require.Equal(t, string(expProtected), string(header))

	payload, err := util.Base64DecodeForJWT(payloadB64)
	require.NoError(t, err)
	require.Equal(t, string(expPayload), string(payload))

	sig, err := util.Base64DecodeForJWT(sigB64)
	require.NoError(t, err)
	require.Equal(t, string(expSig), string(sig))

	// Finally check the ID Token we get matches the ID Token we gave
	require.Equal(t, string(expIdToken), string(idToken))
}

func TestGithubOpFullGQ(t *testing.T) {

	cic := GenCIC(t)

	// Setup expected test data
	expProtected := []byte(`{"alg":"RS256","kid":"1F2AB83404C08EC9EA0BB99DAED02186B091DBF4","typ":"JWT","x5t":"Hyq4NATAjsnqC7mdrtAhhrCR2_Q"}`)
	expPayload := []byte(`{"sub":"repo:example/fake:ref:refs/heads/main","aud":"LJJfahE5cC1AgAWrMkUDL85d0oSSBcP6FJVSulzojds","ref":"refs/heads/main","sha":\"353722c917a3f94988b826b82405ca05feddb1fe","repository":"example/fake","repository_owner":"fakeowner","iss":"https://token.actions.githubusercontent.com","nbf":1709839869,"exp":1709840769,"iat":1709840469}`)

	protected := jws.NewHeaders()
	err := json.Unmarshal(expProtected, protected)
	require.NoError(t, err)

	algOp := jwa.RS256
	signingKey, err := rsa.GenerateKey(rand.Reader, 2048)
	require.NoError(t, err)

	expIdToken, err := jws.Sign(
		expPayload,
		jws.WithKey(
			algOp,
			signingKey,
			jws.WithProtectedHeaders(protected),
		),
	)
	require.NoError(t, err)

	expResponseBody := fmt.Sprintf(`{"count":1857,"value":"%s"}`, expIdToken)
	testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		res.WriteHeader(http.StatusOK)
		_, err := res.Write([]byte(expResponseBody))
		require.NoError(t, err)
	}))
	defer func() { testServer.Close() }()

	tokenRequestURL := testServer.URL
	authToken := "fakeAuthToken"

	jwksFunc, err := discover.MockGetJwksByIssuerOneKey(signingKey.Public(), "1F2AB83404C08EC9EA0BB99DAED02186B091DBF4", string(algOp))
	require.NoError(t, err)

	op := &GithubOp{
		rawTokenRequestURL:    tokenRequestURL,
		tokenRequestAuthToken: authToken,
		publicKeyFinder: discover.PublicKeyFinder{
			JwksFunc: jwksFunc,
		},
	}

	tokens, err := op.RequestTokens(context.Background(), cic)
	require.NoError(t, err)
	idToken := tokens.IDToken
	require.NotNil(t, idToken)

	_, payloadB64, _, err := jws.SplitCompact(idToken)
	require.NoError(t, err)

	headers := extractHeaders(t, idToken)
	require.Equal(t, gq.GQ256, headers.Algorithm(), "github must only return GQ signed ID Tokens but we got (%s)", headers.Algorithm())

	origHeadersB64, err := gq.OriginalJWTHeaders(idToken)
	require.NoError(t, err)
	origHeaders, err := util.Base64DecodeForJWT(origHeadersB64)
	require.NoError(t, err)
	require.Equal(t, string(expProtected), string(origHeaders))

	payload, err := util.Base64DecodeForJWT(payloadB64)
	require.NoError(t, err)
	require.Equal(t, string(expPayload), string(payload))

	// Check that GQ Signature verifies
	rsaKey, ok := signingKey.Public().(*rsa.PublicKey)
	require.True(t, ok)
	ok, err = gq.GQ256VerifyJWT(rsaKey, idToken)
	require.NoError(t, err)
	require.True(t, ok)
}

// Simple test to ensure we don't accidentally break this simple function
func TestBuildTokenURL(t *testing.T) {
	TokenRequestURL := "http://example.com/token-request"
	audience := "fakeAudience"

	tokenURL, err := buildTokenURL(TokenRequestURL, audience)
	require.NoError(t, err)
	require.Equal(t, "http://example.com/token-request?audience=fakeAudience", tokenURL)
}

func extractHeaders(t *testing.T, idToken []byte) jws.Headers {
	headersB64, _, _, err := jws.SplitCompact(idToken)
	require.NoError(t, err)
	headersJson, err := util.Base64DecodeForJWT(headersB64)
	require.NoError(t, err)
	headers := jws.NewHeaders()
	err = json.Unmarshal(headersJson, &headers)
	require.NoError(t, err)
	return headers
}