20862: Merge branch 'main' into 20862-google-api-client
[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.LogCreateRequestFraction":             false,
71         "API.MaxConcurrentRequests":                false,
72         "API.MaxIndexDatabaseRead":                 false,
73         "API.MaxItemsPerResponse":                  true,
74         "API.MaxKeepBlobBuffers":                   false,
75         "API.MaxQueuedRequests":                    false,
76         "API.MaxQueueTimeForLockRequests":          false,
77         "API.MaxRequestAmplification":              false,
78         "API.MaxRequestSize":                       true,
79         "API.MaxTokenLifetime":                     false,
80         "API.RequestTimeout":                       true,
81         "API.SendTimeout":                          true,
82         "API.UnfreezeProjectRequiresAdmin":         true,
83         "API.VocabularyPath":                       false,
84         "API.WebsocketClientEventQueue":            false,
85         "API.WebsocketServerEventQueue":            false,
86         "AuditLogs":                                false,
87         "AuditLogs.MaxAge":                         false,
88         "AuditLogs.MaxDeleteBatch":                 false,
89         "AuditLogs.UnloggedAttributes":             false,
90         "ClusterID":                                true,
91         "Collections":                              true,
92         "Collections.BalanceCollectionBatch":       false,
93         "Collections.BalanceCollectionBuffers":     false,
94         "Collections.BalancePeriod":                false,
95         "Collections.BalanceTimeout":               false,
96         "Collections.BalanceUpdateLimit":           false,
97         "Collections.BlobDeleteConcurrency":        false,
98         "Collections.BlobMissingReport":            false,
99         "Collections.BlobReplicateConcurrency":     false,
100         "Collections.BlobSigning":                  true,
101         "Collections.BlobSigningKey":               false,
102         "Collections.BlobSigningTTL":               true,
103         "Collections.BlobTrash":                    false,
104         "Collections.BlobTrashCheckInterval":       false,
105         "Collections.BlobTrashConcurrency":         false,
106         "Collections.BlobTrashLifetime":            false,
107         "Collections.CollectionVersioning":         true,
108         "Collections.DefaultReplication":           true,
109         "Collections.DefaultTrashLifetime":         true,
110         "Collections.ForwardSlashNameSubstitution": true,
111         "Collections.KeepproxyPermission":          false,
112         "Collections.ManagedProperties":            true,
113         "Collections.ManagedProperties.*":          true,
114         "Collections.ManagedProperties.*.*":        true,
115         "Collections.PreserveVersionIfIdle":        true,
116         "Collections.S3FolderObjects":              true,
117         "Collections.TrashSweepInterval":           false,
118         "Collections.TrustAllContent":              true,
119         "Collections.WebDAVCache":                  false,
120         "Collections.WebDAVLogEvents":              false,
121         "Collections.WebDAVPermission":             false,
122         "Containers":                               true,
123         "Containers.AlwaysUsePreemptibleInstances": true,
124         "Containers.CloudVMs":                      false,
125         "Containers.CrunchRunArgumentsList":        false,
126         "Containers.CrunchRunCommand":              false,
127         "Containers.DefaultKeepCacheRAM":           true,
128         "Containers.DispatchPrivateKey":            false,
129         "Containers.JobsAPI":                       true,
130         "Containers.JobsAPI.Enable":                true,
131         "Containers.JobsAPI.GitInternalDir":        false,
132         "Containers.LocalKeepBlobBuffersPerVCPU":   false,
133         "Containers.LocalKeepLogsToContainerLog":   false,
134         "Containers.Logging":                       false,
135         "Containers.LogReuseDecisions":             false,
136         "Containers.LSF":                           false,
137         "Containers.MaxDispatchAttempts":           false,
138         "Containers.MaxRetryAttempts":              true,
139         "Containers.MinRetryPeriod":                true,
140         "Containers.PreemptiblePriceFactor":        false,
141         "Containers.ReserveExtraRAM":               true,
142         "Containers.RuntimeEngine":                 true,
143         "Containers.ShellAccess":                   true,
144         "Containers.ShellAccess.Admin":             true,
145         "Containers.ShellAccess.User":              true,
146         "Containers.SLURM":                         false,
147         "Containers.StaleLockTimeout":              false,
148         "Containers.SupportedDockerImageFormats":   true,
149         "Containers.SupportedDockerImageFormats.*": true,
150         "Git":                                  false,
151         "InstanceTypes":                        true,
152         "InstanceTypes.*":                      true,
153         "InstanceTypes.*.*":                    true,
154         "InstanceTypes.*.*.*":                  true,
155         "Login":                                true,
156         "Login.Google":                         true,
157         "Login.Google.AlternateEmailAddresses": false,
158         "Login.Google.AuthenticationRequestParameters":        false,
159         "Login.Google.ClientID":                               false,
160         "Login.Google.ClientSecret":                           false,
161         "Login.Google.Enable":                                 true,
162         "Login.IssueTrustedTokens":                            false,
163         "Login.LDAP":                                          true,
164         "Login.LDAP.AppendDomain":                             false,
165         "Login.LDAP.EmailAttribute":                           false,
166         "Login.LDAP.Enable":                                   true,
167         "Login.LDAP.InsecureTLS":                              false,
168         "Login.LDAP.MinTLSVersion":                            false,
169         "Login.LDAP.SearchAttribute":                          false,
170         "Login.LDAP.SearchBase":                               false,
171         "Login.LDAP.SearchBindPassword":                       false,
172         "Login.LDAP.SearchBindUser":                           false,
173         "Login.LDAP.SearchFilters":                            false,
174         "Login.LDAP.StartTLS":                                 false,
175         "Login.LDAP.StripDomain":                              false,
176         "Login.LDAP.URL":                                      false,
177         "Login.LDAP.UsernameAttribute":                        false,
178         "Login.LoginCluster":                                  true,
179         "Login.OpenIDConnect":                                 true,
180         "Login.OpenIDConnect.AcceptAccessToken":               false,
181         "Login.OpenIDConnect.AcceptAccessTokenScope":          false,
182         "Login.OpenIDConnect.AuthenticationRequestParameters": false,
183         "Login.OpenIDConnect.ClientID":                        false,
184         "Login.OpenIDConnect.ClientSecret":                    false,
185         "Login.OpenIDConnect.EmailClaim":                      false,
186         "Login.OpenIDConnect.EmailVerifiedClaim":              false,
187         "Login.OpenIDConnect.Enable":                          true,
188         "Login.OpenIDConnect.Issuer":                          false,
189         "Login.OpenIDConnect.UsernameClaim":                   false,
190         "Login.PAM":                                           true,
191         "Login.PAM.DefaultEmailDomain":                        false,
192         "Login.PAM.Enable":                                    true,
193         "Login.PAM.Service":                                   false,
194         "Login.RemoteTokenRefresh":                            true,
195         "Login.Test":                                          true,
196         "Login.Test.Enable":                                   true,
197         "Login.Test.Users":                                    false,
198         "Login.TokenLifetime":                                 false,
199         "Login.TrustedClients":                                false,
200         "Login.TrustPrivateNetworks":                          false,
201         "Mail":                                                true,
202         "Mail.EmailFrom":                                      false,
203         "Mail.IssueReporterEmailFrom":                         false,
204         "Mail.IssueReporterEmailTo":                           false,
205         "Mail.MailchimpAPIKey":                                false,
206         "Mail.MailchimpListID":                                false,
207         "Mail.SendUserSetupNotificationEmail":                 false,
208         "Mail.SupportEmailAddress":                            true,
209         "ManagementToken":                                     false,
210         "PostgreSQL":                                          false,
211         "RemoteClusters":                                      true,
212         "RemoteClusters.*":                                    true,
213         "RemoteClusters.*.ActivateUsers":                      true,
214         "RemoteClusters.*.Host":                               true,
215         "RemoteClusters.*.Insecure":                           true,
216         "RemoteClusters.*.Proxy":                              true,
217         "RemoteClusters.*.Scheme":                             true,
218         "Services":                                            true,
219         "Services.*":                                          true,
220         "Services.*.ExternalURL":                              true,
221         "Services.*.InternalURLs":                             false,
222         "StorageClasses":                                      true,
223         "StorageClasses.*":                                    true,
224         "StorageClasses.*.Default":                            true,
225         "StorageClasses.*.Priority":                           true,
226         "SystemLogs":                                          false,
227         "SystemRootToken":                                     false,
228         "TLS":                                                 false,
229         "TLS.Certificate":                                     false,
230         "TLS.Insecure":                                        true,
231         "TLS.Key":                                             false,
232         "Users":                                               true,
233         "Users.ActivatedUsersAreVisibleToOthers":              false,
234         "Users.ActivityLoggingPeriod":                         false,
235         "Users.AdminNotifierEmailFrom":                        false,
236         "Users.AnonymousUserToken":                            true,
237         "Users.AutoAdminFirstUser":                            false,
238         "Users.AutoAdminUserWithEmail":                        false,
239         "Users.AutoSetupNewUsers":                             false,
240         "Users.AutoSetupNewUsersWithRepository":               false,
241         "Users.AutoSetupNewUsersWithVmUUID":                   false,
242         "Users.AutoSetupUsernameBlacklist":                    false,
243         "Users.CanCreateRoleGroups":                           true,
244         "Users.EmailSubjectPrefix":                            false,
245         "Users.NewInactiveUserNotificationRecipients":         false,
246         "Users.NewUserNotificationRecipients":                 false,
247         "Users.NewUsersAreActive":                             false,
248         "Users.PreferDomainForUsername":                       false,
249         "Users.RoleGroupsVisibleToAll":                        false,
250         "Users.SyncIgnoredGroups":                             true,
251         "Users.SyncRequiredGroups":                            true,
252         "Users.SyncUserAccounts":                              true,
253         "Users.SyncUserAPITokens":                             true,
254         "Users.SyncUserGroups":                                true,
255         "Users.SyncUserSSHKeys":                               true,
256         "Users.UserNotifierEmailBcc":                          false,
257         "Users.UserNotifierEmailFrom":                         false,
258         "Users.UserProfileNotificationAddress":                false,
259         "Users.UserSetupMailText":                             false,
260         "Volumes":                                             true,
261         "Volumes.*":                                           true,
262         "Volumes.*.*":                                         false,
263         "Volumes.*.AccessViaHosts":                            true,
264         "Volumes.*.AccessViaHosts.*":                          true,
265         "Volumes.*.AccessViaHosts.*.ReadOnly":                 true,
266         "Volumes.*.ReadOnly":                                  true,
267         "Volumes.*.Replication":                               true,
268         "Volumes.*.StorageClasses":                            true,
269         "Volumes.*.StorageClasses.*":                          true,
270         "Workbench":                                           true,
271         "Workbench.ActivationContactLink":                     false,
272         "Workbench.APIClientConnectTimeout":                   true,
273         "Workbench.APIClientReceiveTimeout":                   true,
274         "Workbench.APIResponseCompression":                    true,
275         "Workbench.ApplicationMimetypesWithViewIcon":          true,
276         "Workbench.ApplicationMimetypesWithViewIcon.*":        true,
277         "Workbench.ArvadosDocsite":                            true,
278         "Workbench.ArvadosPublicDataDocURL":                   true,
279         "Workbench.BannerUUID":                                true,
280         "Workbench.DefaultOpenIdPrefix":                       false,
281         "Workbench.DisableSharingURLsUI":                      true,
282         "Workbench.EnableGettingStartedPopup":                 true,
283         "Workbench.EnablePublicProjectsPage":                  true,
284         "Workbench.FileViewersConfigURL":                      true,
285         "Workbench.IdleTimeout":                               true,
286         "Workbench.InactivePageHTML":                          true,
287         "Workbench.LogViewerMaxBytes":                         true,
288         "Workbench.MultiSiteSearch":                           true,
289         "Workbench.ProfilingEnabled":                          true,
290         "Workbench.Repositories":                              false,
291         "Workbench.RepositoryCache":                           false,
292         "Workbench.RunningJobLogRecordsToFetch":               true,
293         "Workbench.SecretKeyBase":                             false,
294         "Workbench.ShowRecentCollectionsOnDashboard":          true,
295         "Workbench.ShowUserAgreementInline":                   true,
296         "Workbench.ShowUserNotifications":                     true,
297         "Workbench.SiteName":                                  true,
298         "Workbench.SSHHelpHostSuffix":                         true,
299         "Workbench.SSHHelpPageHTML":                           true,
300         "Workbench.Theme":                                     true,
301         "Workbench.UserProfileFormFields":                     true,
302         "Workbench.UserProfileFormFields.*":                   true,
303         "Workbench.UserProfileFormFields.*.*":                 true,
304         "Workbench.UserProfileFormFields.*.*.*":               true,
305         "Workbench.UserProfileFormMessage":                    true,
306         "Workbench.WelcomePageHTML":                           true,
307 }
308
309 func redactUnsafe(m map[string]interface{}, mPrefix, lookupPrefix string) error {
310         var errs []string
311         for k, v := range m {
312                 lookupKey := k
313                 safe, ok := whitelist[lookupPrefix+k]
314                 if !ok {
315                         lookupKey = "*"
316                         safe, ok = whitelist[lookupPrefix+"*"]
317                 }
318                 if !ok {
319                         errs = append(errs, fmt.Sprintf("config bug: key %q not in whitelist map", lookupPrefix+k))
320                         continue
321                 }
322                 if !safe {
323                         delete(m, k)
324                         continue
325                 }
326                 if v, ok := v.(map[string]interface{}); ok {
327                         err := redactUnsafe(v, mPrefix+k+".", lookupPrefix+lookupKey+".")
328                         if err != nil {
329                                 errs = append(errs, err.Error())
330                         }
331                 }
332         }
333         if len(errs) > 0 {
334                 return errors.New(strings.Join(errs, "\n"))
335         }
336         return nil
337 }