~james/core

core/spindle/run_env_test.go -rw-r--r-- 11.8 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package spindle

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"tangled.org/core/idresolver"
	"tangled.org/core/notifier"
	"tangled.org/core/spindle/config"
	"tangled.org/core/spindle/db"
	"tangled.org/core/spindle/models"
	"tangled.org/core/spindle/observability"
	"tangled.org/core/spindle/oidc"
	"tangled.org/core/spindle/pemkey/pemkeytest"
	"tangled.org/core/spindle/secrets"
	"tangled.org/core/workflow"
)

const (
	oidcTestIssuerURL = "https://tokens.spindle.tangled.sh"
	oidcTestAudience  = "//iam.googleapis.com/projects/tangled-prod/locations/global/workloadIdentityPools/ci/providers/spindle"
	oidcTestSha       = "1111111111111111111111111111111111111111"
	oidcTestRepoDid   = "did:plc:boltless"
	oidcTestActor     = "did:plc:pusher"
)

func oidcTestIssuer(t *testing.T) *oidc.Issuer {
	t.Helper()
	path, _ := pemkeytest.WriteP256(t)
	issuer, err := oidc.New(oidc.Options{Issuer: oidcTestIssuerURL, KeyPath: path})
	if err != nil {
		t.Fatal(err)
	}
	return issuer
}

func oidcTestPushJob(workflowYaml string) *db.JobRow {
	repoDid, actor := oidcTestRepoDid, oidcTestActor
	return &db.JobRow{
		Id:         42,
		PipelineId: models.PipelineId("3mrkp6iz6os2o"),
		RepoDid:    oidcTestRepoDid,
		Tpl: workflow.PipelineSpec{
			TriggerMetadata: &workflow.TriggerMetadata{
				Kind:  "push",
				Actor: &actor,
				Push:  &workflow.PushTriggerData{Ref: "refs/heads/main", NewSha: oidcTestSha, OldSha: strings.Repeat("0", 40)},
				Repo: &workflow.TriggerRepo{
					Knot:          "knot.test",
					Did:           "did:plc:owner",
					RepoDid:       &repoDid,
					DefaultBranch: "main",
				},
			},
			Workflows: []*workflow.WorkflowSpec{{Name: "test", Engine: "nixery", Raw: workflowYaml}},
		},
	}
}

func oidcTestSpindle(issuer *oidc.Issuer) *Spindle {
	return &Spindle{oidc: issuer, l: slog.New(slog.NewTextHandler(io.Discard, nil))}
}

func decodeJWTClaims(t *testing.T, token string) map[string]any {
	t.Helper()
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		t.Fatalf("token has %d parts, want 3", len(parts))
	}
	raw, err := base64.RawURLEncoding.DecodeString(parts[1])
	if err != nil {
		t.Fatal(err)
	}
	claims := map[string]any{}
	if err := json.Unmarshal(raw, &claims); err != nil {
		t.Fatal(err)
	}
	return claims
}

func TestRunIDTokenMintsFromTheRunRecord(t *testing.T) {
	s := oidcTestSpindle(oidcTestIssuer(t))

	job := oidcTestPushJob(`on: push
env:
  TANGLED_REF: refs/heads/evil
  TANGLED_REPO_REPO_DID: did:plc:forged
  TANGLED_ID_TOKEN: smuggled
`)
	token, err := mintFrom(t, s, job, true)
	if err != nil {
		t.Fatal(err)
	}
	if token == "" {
		t.Fatal("a trusted in-repo run got no ID token")
	}

	claims := decodeJWTClaims(t, token)
	want := map[string]any{
		"iss":        oidcTestIssuerURL,
		"aud":        oidcTestAudience,
		"sub":        oidcTestRepoDid + ":refs/heads/main",
		"repository": oidcTestRepoDid,
		"ref":        "refs/heads/main",
		"actor":      oidcTestActor,
		"sha":        oidcTestSha,
	}
	for name, want := range want {
		if got := claims[name]; got != want {
			t.Errorf("%s claim = %v, want %v (claims come from the run record, not the workflow definition)", name, got, want)
		}
	}
	for _, name := range []string{"iat", "nbf", "exp", "jti"} {
		if claims[name] == nil {
			t.Errorf("%s claim is missing", name)
		}
	}
	if exp, iat := claims["exp"].(float64), claims["iat"].(float64); exp-iat != 900 {
		t.Errorf("lifetime = %v, want a run-scoped 900s", exp-iat)
	}
}

func TestRunIDTokenNeedsATrustedSource(t *testing.T) {
	s := oidcTestSpindle(oidcTestIssuer(t))
	sourceDid := "did:plc:elsewhere"

	// the shape resolveCheckout produces when a manual trigger names somebody
	// else's repository: the checkout, and every source-side env var, is the
	// other repo
	fork := oidcTestPushJob("")
	fork.SourceRepo = &workflow.TriggerRepo{RepoDid: &sourceDid, Did: sourceDid, Knot: "knot.test"}

	if token, err := mintFrom(t, s, fork, false); err != nil || token != "" {
		t.Fatalf("token = %q err = %v, want no token for an untrusted run", token, err)
	}

	// the same record on a trusted run mints, so the assertions above pin the
	// gate and not a broken fixture
	if token, err := mintFrom(t, s, fork, true); err != nil || token == "" {
		t.Fatalf("token = %q err = %v, want a token for the same record when the source is trusted", token, err)
	}
}

func TestRunIDTokenClaimsTheRunRepoNotTheSourceRepo(t *testing.T) {
	s := oidcTestSpindle(oidcTestIssuer(t))
	sourceDid := "did:plc:source"

	job := oidcTestPushJob("")
	job.Tpl.TriggerMetadata.SourceRepo = &sourceDid
	job.Tpl.TriggerMetadata.Repo.RepoDid = &sourceDid

	token, err := mintFrom(t, s, job, true)
	if err != nil {
		t.Fatal(err)
	}
	if got := decodeJWTClaims(t, token)["repository"]; got != oidcTestRepoDid {
		t.Fatalf("repository claim = %v, want the run's own repository %q", got, oidcTestRepoDid)
	}
}

func TestRunIDTokenSignsTheManualRef(t *testing.T) {
	s := oidcTestSpindle(oidcTestIssuer(t))
	actor, ref := oidcTestActor, "refs/heads/main"
	repoDid := oidcTestRepoDid
	// the shape TriggerManual records once it verified the ref's history
	// contains the sha: the ref is the server's observation, not a claim
	job := &db.JobRow{
		Id:         9,
		PipelineId: models.PipelineId("3mrkp6iz6os2o"),
		RepoDid:    oidcTestRepoDid,
		Tpl: workflow.PipelineSpec{
			TriggerMetadata: &workflow.TriggerMetadata{
				Kind:   "manual",
				Actor:  &actor,
				Repo:   &workflow.TriggerRepo{RepoDid: &repoDid, Did: "did:plc:owner", Knot: "knot.test"},
				Manual: &workflow.ManualTriggerData{Sha: oidcTestSha, Ref: &ref},
			},
		},
	}

	token, err := mintFrom(t, s, job, true)
	if err != nil {
		t.Fatal(err)
	}
	claims := decodeJWTClaims(t, token)
	if claims["ref"] != "refs/heads/main" {
		t.Fatalf("ref claim = %v, want the ref the trigger verified", claims["ref"])
	}
	if claims["sub"] != oidcTestRepoDid+":refs/heads/main" {
		t.Fatalf("sub claim = %v, want the verified repo:ref subject", claims["sub"])
	}
	if claims["sha"] != oidcTestSha {
		t.Fatalf("sha claim = %v, want the commit the run targets", claims["sha"])
	}
}

func TestRunIDTokenSkipsRunsWithoutAnIdentity(t *testing.T) {
	s := oidcTestSpindle(oidcTestIssuer(t))

	recordingless := oidcTestPushJob("")
	recordingless.Tpl.TriggerMetadata = nil
	if token, err := mintFrom(t, s, recordingless, true); err != nil || token != "" {
		t.Fatalf("token = %q err = %v, want no token for a run without a record", token, err)
	}

	commitless := oidcTestPushJob("")
	commitless.Tpl.TriggerMetadata.Push.NewSha = ""
	if token, err := mintFrom(t, s, commitless, true); err != nil || token != "" {
		t.Fatalf("token = %q err = %v, want no token for a run without a commit", token, err)
	}

	unconfigured := oidcTestSpindle(nil)
	if token, err := mintFrom(t, unconfigured, oidcTestPushJob(""), true); err != nil || token != "" {
		t.Fatalf("token = %q err = %v, want no token without a configured issuer", token, err)
	}
}

// an identity the issuer refuses to sign must leave the run alone: no token,
// no error. A push to a legal-but-long refname lands here.
func TestIDTokenMinterWithholdsAnUnsignableRun(t *testing.T) {
	s := oidcTestSpindle(oidcTestIssuer(t))

	job := oidcTestPushJob("")
	job.Tpl.TriggerMetadata.Push.Ref = "refs/heads/" + strings.Repeat("nested/", 80) + "main"

	minter := s.idTokenMinter(job, true)
	if minter == nil {
		t.Fatal("a trusted in-repo run with an unsignable ref should still try to mint")
	}
	token, err := minter(10*time.Minute, oidcTestAudience)
	if err != nil {
		t.Fatalf("err = %v, want the run to proceed without a token", err)
	}
	if token != "" {
		t.Fatalf("token = %q, want none for a ref the issuer will not sign", token)
	}
}

type recordingStep struct{}

func (recordingStep) Name() string    { return "record" }
func (recordingStep) Command() string { return "true" }
func (recordingStep) Kind() models.StepKind {
	return models.StepKindUser
}

type recordingEngine struct {
	seen map[string]string
}

func (e *recordingEngine) InitWorkflow(twf workflow.WorkflowSpec, _ workflow.PipelineSpec) (*models.Workflow, error) {
	return &models.Workflow{Name: twf.Name, Steps: []models.Step{recordingStep{}}}, nil
}

func (e *recordingEngine) SetupWorkflow(context.Context, models.WorkflowId, *models.Workflow, models.WorkflowLogger) error {
	return nil
}

func (e *recordingEngine) WorkflowTimeout() time.Duration { return time.Minute }

func (e *recordingEngine) DestroyWorkflow(context.Context, models.WorkflowId) error { return nil }

func (e *recordingEngine) RunStep(_ context.Context, wid models.WorkflowId, w *models.Workflow, _ int, _ []secrets.UnlockedSecret, _ models.WorkflowLogger) error {
	if e.seen == nil {
		e.seen = map[string]string{}
	}
	e.seen[wid.Name] = w.Audience
	return nil
}

func TestRunJobCarriesTheDeclaredAudienceToTheEngine(t *testing.T) {
	dbDir := t.TempDir()
	ctx := context.Background()
	d, err := db.Make(ctx, filepath.Join(dbDir, "spindle.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { d.Close() })

	logDir := t.TempDir()
	cfg := &config.Config{}
	cfg.Server.LogDir = logDir

	rec := &recordingEngine{}
	s := &Spindle{
		l:       slog.New(slog.NewTextHandler(io.Discard, nil)),
		metrics: observability.NewMetrics(),
		db:      d,
		n:       &notifier.Notifier{},
		cfg:     cfg,
		engs:    map[string]models.Engine{"record": rec},
	}

	sourceDid := "did:plc:elsewhere"
	audience := oidcTestAudience
	job := oidcTestPushJob("")
	job.SourceRepo = &workflow.TriggerRepo{RepoDid: &sourceDid, Did: sourceDid, Knot: "knot.test"}
	job.Tpl.Workflows[0].Engine = "record"
	job.Tpl.Workflows[0].Audience = &audience

	s.runJob(ctx, job)

	if got := rec.seen["test"]; got != audience {
		t.Fatalf("engine saw audience %q, want the workflow record's %q", got, audience)
	}
}

// mintFrom runs the minter a workflow would call, and reports a missing minter
// as an empty token so the trust-gate assertions read the same either way.
func mintFrom(t *testing.T, s *Spindle, job *db.JobRow, trusted bool) (string, error) {
	t.Helper()
	minter := s.idTokenMinter(job, trusted)
	if minter == nil {
		return "", nil
	}
	return minter(10*time.Minute, oidcTestAudience)
}

func TestRouterServesTheIssuerSurface(t *testing.T) {
	s := &Spindle{
		cfg:     &config.Config{Role: config.RoleMill},
		l:       slog.New(slog.NewTextHandler(io.Discard, nil)),
		metrics: observability.NewMetrics(),
		res:     idresolver.NewMockResolver(idresolver.MockDirectory{}),
		oidc:    oidcTestIssuer(t),
	}
	router := s.Router()

	fetch := func(path string) *httptest.ResponseRecorder {
		rec := httptest.NewRecorder()
		router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
		return rec
	}

	for _, path := range []string{"/token", "/jwks/", "/.well-known/other"} {
		if rec := fetch(path); rec.Code != http.StatusNotFound {
			t.Errorf("GET %s = %d, want 404: the issuer serves nothing but the discovery document and the key set", path, rec.Code)
		}
	}

	var doc struct {
		Issuer  string   `json:"issuer"`
		JWKSURI string   `json:"jwks_uri"`
		Algs    []string `json:"id_token_signing_alg_values_supported"`
	}
	rec := fetch(oidc.ConfigurationPath)
	if rec.Code != http.StatusOK {
		t.Fatalf("GET %s = %d, want 200", oidc.ConfigurationPath, rec.Code)
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil {
		t.Fatal(err)
	}
	if doc.Issuer != oidcTestIssuerURL || len(doc.Algs) != 1 || doc.Algs[0] != "ES256" {
		t.Errorf("discovery document = %+v, want issuer %q signing with ES256", doc, oidcTestIssuerURL)
	}

	rec = fetch(oidc.JWKSPath)
	if rec.Code != http.StatusOK {
		t.Fatalf("GET %s = %d, want 200", oidc.JWKSPath, rec.Code)
	}
	var set struct {
		Keys []struct {
			KeyID string `json:"kid"`
			Alg   string `json:"alg"`
		} `json:"keys"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &set); err != nil {
		t.Fatal(err)
	}
	if len(set.Keys) != 1 || set.Keys[0].Alg != "ES256" {
		t.Fatalf("key set = %+v, want one ES256 key", set.Keys)
	}
}