-
Notifications
You must be signed in to change notification settings - Fork 63
/
kraftcloud.go
77 lines (63 loc) · 2.15 KB
/
kraftcloud.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package config
import (
"context"
"encoding/base64"
"fmt"
"strings"
)
// GetKraftCloudLogin is a utility method which retrieves credentials of a
// KraftCloud user from the given context returning it in AuthConfig format.
func GetKraftCloudAuthConfig(ctx context.Context, flagToken string) (*AuthConfig, error) {
auth := AuthConfig{
Endpoint: "index.unikraft.io",
VerifySSL: true,
}
// Prioritize environmental variables
if flagToken != "" {
data, err := base64.StdEncoding.DecodeString(flagToken)
if err != nil {
return nil, fmt.Errorf("could not decode token: %w", err)
}
split := strings.Split(string(data), ":")
if len(split) != 2 {
return nil, fmt.Errorf("invalid token format")
}
auth.User = split[0]
auth.Token = split[1]
if G[KraftKit](ctx).Auth == nil {
authMap := map[string]AuthConfig{}
authMap["index.unikraft.io"] = auth
(*G[KraftKit](ctx)).Auth = authMap
} else {
G[KraftKit](ctx).Auth["index.unikraft.io"] = auth
}
// Fallback to local config
} else if auth, ok := G[KraftKit](ctx).Auth["index.unikraft.io"]; ok {
return &auth, nil
} else {
return nil, fmt.Errorf("could not determine kraftcloud user token: try setting `KRAFTCLOUD_TOKEN`")
}
return &auth, nil
}
// GetKraftCloudTokenAuthConfig is a utility method which returns the
// token of the KraftCloud user based on an AuthConfig.
func GetKraftCloudTokenAuthConfig(auth AuthConfig) string {
return base64.StdEncoding.EncodeToString([]byte(auth.User + ":" + auth.Token))
}
// HydrateKraftCloudAuthInContext saturates the context with an additional
// KraftCloud-specific information.
func HydrateKraftCloudAuthInContext(ctx context.Context) (context.Context, error) {
auth, err := GetKraftCloudAuthConfig(ctx, "")
if err != nil {
return nil, err
}
if G[KraftKit](ctx).Auth == nil {
G[KraftKit](ctx).Auth = make(map[string]AuthConfig)
}
G[KraftKit](ctx).Auth["index.unikraft.io"] = *auth
return ctx, nil
}