-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathauth.go
93 lines (81 loc) · 2.54 KB
/
auth.go
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
package agentauth
import (
"context"
"fmt"
"maps"
"os"
"path"
dockerconfig "github.com/docker/cli/cli/config"
"github.com/glasskube/distr/api"
"github.com/google/uuid"
"oras.land/oras-go/pkg/auth"
dockerauth "oras.land/oras-go/pkg/auth/docker"
)
var previousAuth = map[uuid.UUID]map[string]api.AgentRegistryAuth{}
var authClients = map[uuid.UUID]auth.Client{}
func EnsureAuth(
ctx context.Context,
distrRegistryHost, jwt string,
deployment api.AgentDeployment,
) (auth.Client, error) {
if err := os.MkdirAll(DockerConfigDir(deployment), 0o700); err != nil {
return nil, fmt.Errorf("could not create docker config dir for deployment: %w", err)
}
var client auth.Client
if c, exists := authClients[deployment.ID]; exists {
client = c
} else {
if c, err := dockerauth.NewClientWithDockerFallback(DockerConfigPath(deployment)); err != nil {
return nil, fmt.Errorf("could not create auth client: %w", err)
} else {
authClients[deployment.ID] = c
client = c
}
if distrRegistryHost != "" {
client.LoginWithOpts(
auth.WithLoginContext(ctx),
auth.WithLoginInsecure(),
auth.WithLoginHostname(distrRegistryHost),
auth.WithLoginUsername("unused"),
auth.WithLoginSecret(jwt),
)
}
}
if !maps.Equal(previousAuth[deployment.ID], deployment.RegistryAuth) {
for url, registry := range deployment.RegistryAuth {
if err := client.LoginWithOpts(
auth.WithLoginContext(ctx),
auth.WithLoginHostname(url),
auth.WithLoginUsername(registry.Username),
auth.WithLoginSecret(registry.Password),
); err != nil {
return nil, fmt.Errorf("docker login failed for %v: %w", url, err)
}
}
for url := range previousAuth[deployment.ID] {
if _, exists := deployment.RegistryAuth[url]; !exists {
if err := client.Logout(ctx, url); err != nil {
return nil, fmt.Errorf("docker logout failed for %v: %w", url, err)
}
}
}
previousAuth[deployment.ID] = deployment.RegistryAuth
}
return client, nil
}
func DeploymentTempDir(deployment api.AgentDeployment) string {
return path.Join(os.TempDir(), deployment.ID.String())
}
func DockerConfigDir(deployment api.AgentDeployment) string {
return path.Join(DeploymentTempDir(deployment), "docker")
}
func DockerConfigPath(deployment api.AgentDeployment) string {
return path.Join(DockerConfigDir(deployment), dockerconfig.ConfigFileName)
}
func DockerConfigEnv(deployment api.AgentDeployment) []string {
if len(deployment.RegistryAuth) > 0 {
return []string{dockerconfig.EnvOverrideConfigDir + "=" + DockerConfigDir(deployment)}
} else {
return nil
}
}