-
Notifications
You must be signed in to change notification settings - Fork 9
/
naming.go
224 lines (179 loc) · 5.64 KB
/
naming.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package runtime
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"namespacelabs.dev/foundation/internal/certificates"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnapi"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/workspace/dirs"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/cfg"
)
const (
LocalBaseDomain = "nslocal.host"
CloudBaseDomain = "nscloud.dev"
)
var (
NamingNoTLS = false // Set to true in CI.
ReuseStoredCertificates = true
WorkInProgressUseShortAlias = false
)
var errLogin = fnerrors.UsageError("Please run `ns login` to login.",
"Namespace automatically manages nscloud.dev-based sub-domains and issues SSL certificates on your behalf. To use these features, you'll need to login to Namespace using your Github account.")
func ComputeNaming(ctx context.Context, ws string, env cfg.Context, cluster Planner, source *schema.Naming) (*schema.ComputedNaming, error) {
result, err := computeNaming(ctx, ws, env, cluster, source)
if err != nil {
return nil, err
}
fmt.Fprintf(console.Debug(ctx), "computed naming: %+v\n", result)
return result, nil
}
func computeNaming(ctx context.Context, workspace string, env cfg.Context, cluster Planner, source *schema.Naming) (*schema.ComputedNaming, error) {
naming, err := computeInnerNaming(ctx, env, cluster, source)
if err != nil {
return nil, err
}
naming.MainModuleName = workspace
naming.UseShortAlias = naming.GetUseShortAlias() || WorkInProgressUseShortAlias
return naming, nil
}
func computeInnerNaming(ctx context.Context, rootenv cfg.Context, cluster Planner, source *schema.Naming) (*schema.ComputedNaming, error) {
base, err := cluster.ComputeBaseNaming(source)
if err != nil {
return nil, err
}
if base != nil {
return base, nil
}
env := rootenv.Environment()
if env.Purpose != schema.Environment_PRODUCTION {
return &schema.ComputedNaming{
Source: source,
BaseDomain: LocalBaseDomain,
Managed: schema.Domain_LOCAL_MANAGED,
}, nil
}
if !source.GetEnableNamespaceManaged() {
return &schema.ComputedNaming{}, nil
}
userAuth, err := fnapi.LoadUser()
if err != nil {
if errors.Is(err, fnapi.ErrRelogin) {
return nil, errLogin
}
return nil, err
}
org := userAuth.Org
if org == "" {
org = userAuth.Username
}
if env.Purpose == schema.Environment_PRODUCTION {
if orgOverride := source.GetWithOrg(); orgOverride != "" {
org = orgOverride
}
}
return &schema.ComputedNaming{
Source: source,
BaseDomain: fmt.Sprintf("%s.%s", org, CloudBaseDomain),
Managed: schema.Domain_CLOUD_MANAGED,
}, nil
}
func allocateName(ctx context.Context, srv Deployable, opts fnapi.AllocateOpts) (*schema.Certificate, error) {
var cacheKey string
if opts.Subdomain != "" {
if opts.Org == "" {
return nil, fnerrors.InternalError("%s: org must be specified", opts.Subdomain)
}
cacheKey = opts.Subdomain + ".wildcard"
} else if opts.FQDN != "" {
cacheKey = opts.FQDN
} else {
return nil, fnerrors.BadInputError("either FQDN or Subdomain must be set")
}
previous, _ := checkStored(ctx, srv, opts.Org, cacheKey)
if ReuseStoredCertificates {
if previous != nil && isResourceValid(previous) {
// We ignore errors.
return certFromResource(previous), nil
}
}
opts.NoTLS = NamingNoTLS
opts.Stored = previous
opts.Scope = schema.PackageName(srv.GetPackageName())
nr, err := fnapi.AllocateName(ctx, opts)
if err != nil {
return nil, err
}
if err := storeCert(ctx, srv, opts.Org, cacheKey, nr); err != nil {
fmt.Fprintf(console.Warnings(ctx), "failed to persistent certificate for cacheKey=%s: %v\n", cacheKey, err)
}
return certFromResource(nr), nil
}
func certFromResource(res *fnapi.NameResource) *schema.Certificate {
if res.Certificate.PrivateKey != nil && res.Certificate.CertificateBundle != nil {
return &schema.Certificate{
PrivateKey: res.Certificate.PrivateKey,
CertificateBundle: res.Certificate.CertificateBundle,
}
}
return nil
}
func isResourceValid(nr *fnapi.NameResource) bool {
if nr.Certificate.PrivateKey != nil && nr.Certificate.CertificateBundle != nil {
valid, _, _ := certificates.CertIsValid(nr.Certificate.CertificateBundle)
return valid
}
return false
}
func checkStored(ctx context.Context, srv Deployable, org, cacheKey string) (*fnapi.NameResource, error) {
// XXX security check permissions
certDir, err := makeCertDir(org, srv)
if err != nil {
return nil, err
}
// XXX security check escape
contents, err := os.ReadFile(filepath.Join(certDir, cacheKey+".json"))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var nr fnapi.NameResource
if err := json.Unmarshal(contents, &nr); err != nil {
return nil, err
}
return &nr, nil
}
func storeCert(ctx context.Context, srv Deployable, org, cacheKey string, res *fnapi.NameResource) error {
certDir, err := makeCertDir(org, srv)
if err != nil {
return err
}
resBytes, err := json.MarshalIndent(res, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(certDir, os.ModeDir|0700); err != nil {
return err
}
return os.WriteFile(filepath.Join(certDir, cacheKey+".json"), resBytes, 0600)
}
func makeCertDir(org string, srv Deployable) (string, error) {
if org == "" {
return "", fnerrors.New("no org specified")
}
certDir, err := dirs.CertCache()
if err != nil {
return "", err
}
return filepath.Join(certDir, org, srv.GetId()), nil
}