//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")
}
}