1package agent
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "github.com/patriceckhart/zot/packages/provider/auth"
13)
14
15func TestAgentAPIKeyCommandHelperProcess(t *testing.T) {
16 if os.Getenv("ZOT_AGENT_API_KEY_COMMAND_HELPER") != "1" {
17 return
18 }
19 args := os.Args
20 for len(args) > 0 && args[0] != "--" {
21 args = args[1:]
22 }
23 if len(args) != 2 {
24 os.Exit(2)
25 }
26 if err := os.WriteFile(args[1], []byte("ran\n"), 0o600); err != nil {
27 os.Exit(3)
28 }
29 fmt.Print("resolved-secret\n")
30 os.Exit(0)
31}
32
33func TestCommandCredentialIsLazy(t *testing.T) {
34 home := t.TempDir()
35 t.Setenv("ZOT_HOME", home)
36 t.Setenv("LAZY_PROVIDER_API_KEY", "")
37 t.Setenv("ZOT_AGENT_API_KEY_COMMAND_HELPER", "1")
38 marker := filepath.Join(home, "command-ran")
39 credentials := auth.Credentials{AdditionalAPIKeyCreds: map[string]auth.ProviderCreds{
40 "lazy-provider": {
41 APIKeyCommand: &auth.APIKeyCommand{
42 Program: os.Args[0],
43 Args: []string{"-test.run=^TestAgentAPIKeyCommandHelperProcess$", "--", marker},
44 },
45 },
46 }}
47 encoded, err := json.Marshal(credentials)
48 if err != nil {
49 t.Fatal(err)
50 }
51 if err := os.WriteFile(AuthPath(), encoded, 0o600); err != nil {
52 t.Fatal(err)
53 }
54
55 if !CredentialAvailable("lazy-provider") {
56 t.Fatal("command-backed credential was not reported as available")
57 }
58 if _, _, err := resolveCredentialForBackground(context.Background(), "lazy-provider"); err == nil {
59 t.Fatal("background resolution unexpectedly returned the command-backed credential")
60 }
61 if _, err := os.Stat(marker); !os.IsNotExist(err) {
62 t.Fatalf("credential command ran during availability checks: %v", err)
63 }
64
65 cred, method, _, err := ResolveCredentialFull("lazy-provider", "")
66 if err != nil {
67 t.Fatal(err)
68 }
69 if cred != "resolved-secret" || method != "apikey" {
70 t.Fatalf("resolved (%q, %q), want command API key", cred, method)
71 }
72 if contents, err := os.ReadFile(marker); err != nil || !strings.Contains(string(contents), "ran") {
73 t.Fatalf("credential command marker = %q, %v", contents, err)
74 }
75}