~james/core

core/spindle/engines/microvm/debugssh_test.go -rw-r--r-- 2.3 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
//go:build linux

package microvm

import (
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"io"
	"log/slog"
	"testing"

	"github.com/bluesky-social/indigo/atproto/syntax"
	gossh "golang.org/x/crypto/ssh"
)

type fakeAuthorizer struct {
	allow bool
	asked []syntax.DID
}

func (f *fakeAuthorizer) DebugKeyAllowed(_ context.Context, repo syntax.DID, _ gossh.PublicKey) bool {
	f.asked = append(f.asked, repo)
	return f.allow
}

func debugTestKey(t *testing.T) gossh.PublicKey {
	t.Helper()
	pub, _, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	key, err := gossh.NewPublicKey(pub)
	if err != nil {
		t.Fatal(err)
	}
	return key
}

func debugTestEngine(target debugTarget) *Engine {
	return &Engine{
		l:     slog.New(slog.NewTextHandler(io.Discard, nil)),
		debug: map[string]debugTarget{"job": target},
	}
}

func TestDebugKeyCheckBoundToTheWorkflowDecidesInsteadOfTheLocalAuthorizer(t *testing.T) {
	key := debugTestKey(t)
	for _, allow := range []bool{true, false} {
		var gotKey []byte
		e := debugTestEngine(debugTarget{repoDid: "did:plc:repo", keyCheck: func(_ context.Context, k []byte) bool {
			gotKey = k
			return allow
		}})
		local := &fakeAuthorizer{allow: !allow}
		e.SetDebugAuthorizer(local)

		if got := e.checkDebugAuth(context.Background(), "job", key); got != allow {
			t.Errorf("mill said %v, checkDebugAuth answered %v", allow, got)
		}
		if string(gotKey) != string(key.Marshal()) {
			t.Error("the check was not given the key's wire form")
		}
		if len(local.asked) != 0 {
			t.Error("the local authorizer was asked although the workflow carries its own check")
		}
	}
}

func TestDebugKeyFallsBackToTheLocalAuthorizerAndRefusesWithoutOne(t *testing.T) {
	key := debugTestKey(t)
	e := debugTestEngine(debugTarget{repoDid: "did:plc:repo"})
	if e.checkDebugAuth(context.Background(), "job", key) {
		t.Fatal("a key got in with no authorizer wired")
	}

	local := &fakeAuthorizer{allow: true}
	e.SetDebugAuthorizer(local)
	if !e.checkDebugAuth(context.Background(), "job", key) {
		t.Fatal("the local authorizer's yes was ignored")
	}
	if len(local.asked) != 1 || local.asked[0] != "did:plc:repo" {
		t.Fatalf("local authorizer asked about %v, want the job's repo", local.asked)
	}
	if e.checkDebugAuth(context.Background(), "unknown-job", key) {
		t.Fatal("a key got in for a job with no live target")
	}
}