Merge branch '19982-spot-instance' refs #19982
[arvados.git] / lib / config / export.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package config
6
7 import (
8         "encoding/json"
9         "errors"
10         "fmt"
11         "io"
12         "strings"
13
14         "git.arvados.org/arvados.git/sdk/go/arvados"
15 )
16
17 // ExportJSON writes a JSON object with the safe (non-secret) portions
18 // of the cluster config to w.
19 func ExportJSON(w io.Writer, cluster *arvados.Cluster) error {
20         buf, err := json.Marshal(cluster)
21         if err != nil {
22                 return err
23         }
24         var m map[string]interface{}
25         err = json.Unmarshal(buf, &m)
26         if err != nil {
27                 return err
28         }
29
30         // ClusterID is not marshalled by default (see `json:"-"`).
31         // Add it back here so it is included in the exported config.
32         m["ClusterID"] = cluster.ClusterID
33         err = redactUnsafe(m, "", "")
34         if err != nil {
35                 return err
36         }
37         return json.NewEncoder(w).Encode(m)
38 }
39
40 // whitelist classifies configs as safe/unsafe to reveal through the API
41 // endpoint. Note that endpoint does not require authentication.
42 //
43 // Every config entry must either be listed explicitly here along with
44 // all of its parent keys (e.g., "API" + "API.RequestTimeout"), or
45 // have an ancestor listed as false (e.g.,
46 // "PostgreSQL.Connection.password" has an ancestor
47 // "PostgreSQL.Connection" with a false value). Otherwise, it is a bug
48 // which should be caught by tests.
49 //
50 // Example: API.RequestTimeout is safe because whitelist["API"] == and
51 // whitelist["API.RequestTimeout"] == true.
52 //
53 // Example: PostgreSQL.Connection.password is not safe because
54 // whitelist["PostgreSQL.Connection"] == false.
55 //
56 // Example: PostgreSQL.BadKey would cause an error because
57 // whitelist["PostgreSQL"] isn't false, and neither
58 // whitelist["PostgreSQL.BadKey"] nor whitelist["PostgreSQL.*"]
59 // exists.
60 var whitelist = map[string]bool{
61         // | sort -t'"' -k2,2
62         "API":                                                 true,
63         "API.AsyncPermissionsUpdateInterval":                  false,
64         "API.DisabledAPIs":                                    false,
65         "API.FreezeProjectRequiresDescription":                true,
66         "API.FreezeProjectRequiresProperties":                 true,
67         "API.FreezeProjectRequiresProperties.*":               true,
68         "API.KeepServiceRequestTimeout":                       false,
69         "API.LockBeforeUpdate":                                false,
70         "API.MaxConcurrentRailsRequests":                      false,
71         "API.MaxConcurrentRequests":                           false,
72         "API.MaxGatewayTunnels":                               false,
73         "API.MaxIndexDatabaseRead":                            false,
74         "API.MaxItemsPerResponse":                             true,
75         "API.MaxKeepBlobBuffers":                              false,
76         "API.MaxQueuedRequests":                               false,
77         "API.MaxQueueTimeForLockRequests":                     false,
78         "API.MaxRequestAmplification":                         false,
79         "API.MaxRequestSize":                                  true,
80         "API.MaxTokenLifetime":                                false,
81         "API.RequestTimeout":                                  true,
82         "API.SendTimeout":                                     true,
83         "API.UnfreezeProjectRequiresAdmin":                    true,
84         "API.VocabularyPath":                                  false,
85         "API.WebsocketClientEventQueue":                       false,
86         "API.WebsocketServerEventQueue":                       false,
87         "AuditLogs":                                           false,
88         "AuditLogs.MaxAge":                                    false,
89         "AuditLogs.MaxDeleteBatch":                            false,
90         "AuditLogs.UnloggedAttributes":                        false,
91         "ClusterID":                                           true,
92         "Collections":                                         true,
93         "Collections.BalanceCollectionBatch":                  false,
94         "Collections.BalanceCollectionBuffers":                false,
95         "Collections.BalancePeriod":                           false,
96         "Collections.BalancePullLimit":                        false,
97         "Collections.BalanceTimeout":                          false,
98         "Collections.BalanceTrashLimit":                       false,
99         "Collections.BalanceUpdateLimit":                      false,
100         "Collections.BlobDeleteConcurrency":                   false,
101         "Collections.BlobMissingReport":                       false,
102         "Collections.BlobReplicateConcurrency":                false,
103         "Collections.BlobSigning":                             true,
104         "Collections.BlobSigningKey":                          false,
105         "Collections.BlobSigningTTL":                          true,
106         "Collections.BlobTrash":                               false,
107         "Collections.BlobTrashCheckInterval":                  false,
108         "Collections.BlobTrashConcurrency":                    false,
109         "Collections.BlobTrashLifetime":                       false,
110         "Collections.CollectionVersioning":                    true,
111         "Collections.DefaultReplication":                      true,
112         "Collections.DefaultTrashLifetime":                    true,
113         "Collections.ForwardSlashNameSubstitution":            true,
114         "Collections.KeepproxyPermission":                     false,
115         "Collections.ManagedProperties":                       true,
116         "Collections.ManagedProperties.*":                     true,
117         "Collections.ManagedProperties.*.*":                   true,
118         "Collections.PreserveVersionIfIdle":                   true,
119         "Collections.S3FolderObjects":                         true,
120         "Collections.TrashSweepInterval":                      false,
121         "Collections.TrustAllContent":                         true,
122         "Collections.WebDAVCache":                             false,
123         "Collections.WebDAVLogEvents":                         false,
124         "Collections.WebDAVOutputBuffer":                      false,
125         "Collections.WebDAVPermission":                        false,
126         "Containers":                                          true,
127         "Containers.AlwaysUsePreemptibleInstances":            true,
128         "Containers.CloudVMs":                                 false,
129         "Containers.CrunchRunArgumentsList":                   false,
130         "Containers.CrunchRunCommand":                         false,
131         "Containers.DefaultKeepCacheRAM":                      true,
132         "Containers.DispatchPrivateKey":                       false,
133         "Containers.LocalKeepBlobBuffersPerVCPU":              false,
134         "Containers.LocalKeepLogsToContainerLog":              false,
135         "Containers.Logging":                                  false,
136         "Containers.LogReuseDecisions":                        false,
137         "Containers.LSF":                                      false,
138         "Containers.MaxDispatchAttempts":                      false,
139         "Containers.MaximumPriceFactor":                       true,
140         "Containers.MaxRetryAttempts":                         true,
141         "Containers.MinRetryPeriod":                           true,
142         "Containers.PreemptiblePriceFactor":                   false,
143         "Containers.ReserveExtraRAM":                          true,
144         "Containers.RuntimeEngine":                            true,
145         "Containers.ShellAccess":                              true,
146         "Containers.ShellAccess.Admin":                        true,
147         "Containers.ShellAccess.User":                         true,
148         "Containers.SLURM":                                    false,
149         "Containers.StaleLockTimeout":                         false,
150         "Containers.SupportedDockerImageFormats":              true,
151         "Containers.SupportedDockerImageFormats.*":            true,
152         "InstanceTypes":                                       true,
153         "InstanceTypes.*":                                     true,
154         "InstanceTypes.*.*":                                   true,
155         "InstanceTypes.*.*.*":                                 true,
156         "Login":                                               true,
157         "Login.Google":                                        true,
158         "Login.Google.AlternateEmailAddresses":                false,
159         "Login.Google.AuthenticationRequestParameters":        false,
160         "Login.Google.ClientID":                               false,
161         "Login.Google.ClientSecret":                           false,
162         "Login.Google.Enable":                                 true,
163         "Login.IssueTrustedTokens":                            false,
164         "Login.LDAP":                                          true,
165         "Login.LDAP.AppendDomain":                             false,
166         "Login.LDAP.EmailAttribute":                           false,
167         "Login.LDAP.Enable":                                   true,
168         "Login.LDAP.InsecureTLS":                              false,
169         "Login.LDAP.MinTLSVersion":                            false,
170         "Login.LDAP.SearchAttribute":                          false,
171         "Login.LDAP.SearchBase":                               false,
172         "Login.LDAP.SearchBindPassword":                       false,
173         "Login.LDAP.SearchBindUser":                           false,
174         "Login.LDAP.SearchFilters":                            false,
175         "Login.LDAP.StartTLS":                                 false,
176         "Login.LDAP.StripDomain":                              false,
177         "Login.LDAP.URL":                                      false,
178         "Login.LDAP.UsernameAttribute":                        false,
179         "Login.LoginCluster":                                  true,
180         "Login.OpenIDConnect":                                 true,
181         "Login.OpenIDConnect.AcceptAccessToken":               false,
182         "Login.OpenIDConnect.AcceptAccessTokenScope":          false,
183         "Login.OpenIDConnect.AuthenticationRequestParameters": false,
184         "Login.OpenIDConnect.ClientID":                        false,
185         "Login.OpenIDConnect.ClientSecret":                    false,
186         "Login.OpenIDConnect.EmailClaim":                      false,
187         "Login.OpenIDConnect.EmailVerifiedClaim":              false,
188         "Login.OpenIDConnect.Enable":                          true,
189         "Login.OpenIDConnect.Issuer":                          false,
190         "Login.OpenIDConnect.UsernameClaim":                   false,
191         "Login.PAM":                                           true,
192         "Login.PAM.DefaultEmailDomain":                        false,
193         "Login.PAM.Enable":                                    true,
194         "Login.PAM.Service":                                   false,
195         "Login.RemoteTokenRefresh":                            true,
196         "Login.Test":                                          true,
197         "Login.Test.Enable":                                   true,
198         "Login.Test.Users":                                    false,
199         "Login.TokenLifetime":                                 false,
200         "Login.TrustedClients":                                false,
201         "Login.TrustPrivateNetworks":                          false,
202         "ManagementToken":                                     false,
203         "PostgreSQL":                                          false,
204         "RemoteClusters":                                      true,
205         "RemoteClusters.*":                                    true,
206         "RemoteClusters.*.ActivateUsers":                      true,
207         "RemoteClusters.*.Host":                               true,
208         "RemoteClusters.*.Insecure":                           true,
209         "RemoteClusters.*.Proxy":                              true,
210         "RemoteClusters.*.Scheme":                             true,
211         "Services":                                            true,
212         "Services.*":                                          true,
213         "Services.*.ExternalURL":                              true,
214         "Services.*.InternalURLs":                             false,
215         "StorageClasses":                                      true,
216         "StorageClasses.*":                                    true,
217         "StorageClasses.*.Default":                            true,
218         "StorageClasses.*.Priority":                           true,
219         "SystemLogs":                                          false,
220         "SystemRootToken":                                     false,
221         "TLS":                                                 false,
222         "TLS.Certificate":                                     false,
223         "TLS.Insecure":                                        true,
224         "TLS.Key":                                             false,
225         "Users":                                               true,
226         "Users.ActivatedUsersAreVisibleToOthers":              false,
227         "Users.ActivityLoggingPeriod":                         false,
228         "Users.AdminNotifierEmailFrom":                        false,
229         "Users.AnonymousUserToken":                            true,
230         "Users.AutoAdminFirstUser":                            false,
231         "Users.AutoAdminUserWithEmail":                        false,
232         "Users.AutoSetupNewUsers":                             false,
233         "Users.AutoSetupNewUsersWithVmUUID":                   false,
234         "Users.AutoSetupUsernameBlacklist":                    false,
235         "Users.CanCreateRoleGroups":                           true,
236         "Users.EmailSubjectPrefix":                            false,
237         "Users.NewInactiveUserNotificationRecipients":         false,
238         "Users.NewUserNotificationRecipients":                 false,
239         "Users.NewUsersAreActive":                             false,
240         "Users.PreferDomainForUsername":                       false,
241         "Users.RoleGroupsVisibleToAll":                        false,
242         "Users.SendUserSetupNotificationEmail":                false,
243         "Users.SupportEmailAddress":                           true,
244         "Users.SyncIgnoredGroups":                             true,
245         "Users.SyncRequiredGroups":                            true,
246         "Users.SyncUserAccounts":                              true,
247         "Users.SyncUserAPITokens":                             true,
248         "Users.SyncUserGroups":                                true,
249         "Users.SyncUserSSHKeys":                               true,
250         "Users.UserNotifierEmailBcc":                          false,
251         "Users.UserNotifierEmailFrom":                         false,
252         "Users.UserProfileNotificationAddress":                false,
253         "Users.UserSetupMailText":                             false,
254         "Volumes":                                             true,
255         "Volumes.*":                                           true,
256         "Volumes.*.*":                                         false,
257         "Volumes.*.AccessViaHosts":                            true,
258         "Volumes.*.AccessViaHosts.*":                          true,
259         "Volumes.*.AccessViaHosts.*.ReadOnly":                 true,
260         "Volumes.*.ReadOnly":                                  true,
261         "Volumes.*.Replication":                               true,
262         "Volumes.*.StorageClasses":                            true,
263         "Volumes.*.StorageClasses.*":                          true,
264         "Workbench":                                           true,
265         "Workbench.ActivationContactLink":                     false,
266         "Workbench.APIClientConnectTimeout":                   true,
267         "Workbench.APIClientReceiveTimeout":                   true,
268         "Workbench.APIResponseCompression":                    true,
269         "Workbench.ApplicationMimetypesWithViewIcon":          true,
270         "Workbench.ApplicationMimetypesWithViewIcon.*":        true,
271         "Workbench.ArvadosDocsite":                            true,
272         "Workbench.ArvadosPublicDataDocURL":                   true,
273         "Workbench.BannerUUID":                                true,
274         "Workbench.DefaultOpenIdPrefix":                       false,
275         "Workbench.DisableSharingURLsUI":                      true,
276         "Workbench.EnableGettingStartedPopup":                 true,
277         "Workbench.EnablePublicProjectsPage":                  true,
278         "Workbench.FileViewersConfigURL":                      true,
279         "Workbench.IdleTimeout":                               true,
280         "Workbench.InactivePageHTML":                          true,
281         "Workbench.LogViewerMaxBytes":                         true,
282         "Workbench.MultiSiteSearch":                           true,
283         "Workbench.ProfilingEnabled":                          true,
284         "Workbench.Repositories":                              false,
285         "Workbench.RepositoryCache":                           false,
286         "Workbench.RunningJobLogRecordsToFetch":               true,
287         "Workbench.ShowRecentCollectionsOnDashboard":          true,
288         "Workbench.ShowUserAgreementInline":                   true,
289         "Workbench.ShowUserNotifications":                     true,
290         "Workbench.SiteName":                                  true,
291         "Workbench.SSHHelpHostSuffix":                         true,
292         "Workbench.SSHHelpPageHTML":                           true,
293         "Workbench.Theme":                                     true,
294         "Workbench.UserProfileFormFields":                     true,
295         "Workbench.UserProfileFormFields.*":                   true,
296         "Workbench.UserProfileFormFields.*.*":                 true,
297         "Workbench.UserProfileFormFields.*.*.*":               true,
298         "Workbench.UserProfileFormMessage":                    true,
299         "Workbench.WelcomePageHTML":                           true,
300 }
301
302 func redactUnsafe(m map[string]interface{}, mPrefix, lookupPrefix string) error {
303         var errs []string
304         for k, v := range m {
305                 lookupKey := k
306                 safe, ok := whitelist[lookupPrefix+k]
307                 if !ok {
308                         lookupKey = "*"
309                         safe, ok = whitelist[lookupPrefix+"*"]
310                 }
311                 if !ok {
312                         errs = append(errs, fmt.Sprintf("config bug: key %q not in whitelist map", lookupPrefix+k))
313                         continue
314                 }
315                 if !safe {
316                         delete(m, k)
317                         continue
318                 }
319                 if v, ok := v.(map[string]interface{}); ok {
320                         err := redactUnsafe(v, mPrefix+k+".", lookupPrefix+lookupKey+".")
321                         if err != nil {
322                                 errs = append(errs, err.Error())
323                         }
324                 }
325         }
326         if len(errs) > 0 {
327                 return errors.New(strings.Join(errs, "\n"))
328         }
329         return nil
330 }