/
root.go
251 lines (219 loc) · 8.21 KB
/
root.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright (c) 2020, Amazon.com, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package cmd ...
package cmd
import (
"context"
"fmt"
"os"
"github.com/awslabs/ssosync/internal"
"github.com/awslabs/ssosync/internal/config"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-sdk-go/service/codepipeline"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/secretsmanager"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
version = "dev"
commit = "none"
date = "unknown"
builtBy = "unknown"
)
var cfg *config.Config
var rootCmd = &cobra.Command{
Version: "dev",
Use: "ssosync",
Short: "SSO Sync, making AWS SSO be populated automagically",
Long: `A command line tool to enable you to synchronise your Google
Apps (Google Workspace) users to AWS Single Sign-on (AWS SSO)
Complete documentation is available at https://github.com/awslabs/ssosync`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := internal.DoSync(ctx, cfg)
if err != nil {
return err
}
return nil
},
}
// Execute is the entry point of the command. If we are
// running inside of AWS Lambda, we use the Lambda
// execution path.
func Execute() {
if cfg.IsLambda {
log.Info("Executing as Lambda")
lambda.Start(Handler)
}
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func Handler(ctx context.Context, event events.CodePipelineEvent) (string, error) {
log.Debug(event)
err := rootCmd.Execute()
s := session.Must(session.NewSession())
cpl := codepipeline.New(s)
cfg.IsLambdaRunningInCodePipeline = len(event.CodePipelineJob.ID) > 0
if cfg.IsLambdaRunningInCodePipeline {
log.Info("Lambda has been invoked by CodePipeline")
if err != nil {
// notify codepipeline and mark its job execution as Failure
log.Fatalf(errors.Wrap(err, "Notifying CodePipeline and mark its job execution as Failure").Error())
jobID := event.CodePipelineJob.ID
if len(jobID) == 0 {
panic("CodePipeline Job ID is not set")
}
// mark the job as Failure.
cplFailure := &codepipeline.PutJobFailureResultInput{
JobId: aws.String(jobID),
FailureDetails: &codepipeline.FailureDetails{
Message: aws.String(err.Error()),
Type: aws.String("JobFailed"),
},
}
_, cplErr := cpl.PutJobFailureResult(cplFailure)
if cplErr != nil {
log.Fatalf(errors.Wrap(err, "Failed to update CodePipeline jobID status").Error())
}
return "Failure", err
} else {
log.Info("Notifying CodePipeline and mark its job execution as Success")
jobID := event.CodePipelineJob.ID
if len(jobID) == 0 {
panic("CodePipeline Job ID is not set")
}
// mark the job as Success.
cplSuccess := &codepipeline.PutJobSuccessResultInput{
JobId: aws.String(jobID),
}
_, cplErr := cpl.PutJobSuccessResult(cplSuccess)
if cplErr != nil {
log.Fatalf(errors.Wrap(err, "Failed to update CodePipeline jobID status").Error())
}
return "Success", nil
}
} else {
if err != nil {
return "Failure", err
} else {
return "Success", nil
}
}
}
func init() {
// init config
cfg = config.New()
cfg.IsLambda = len(os.Getenv("_LAMBDA_SERVER_PORT")) > 0
// initialize cobra
cobra.OnInitialize(initConfig)
addFlags(rootCmd, cfg)
rootCmd.SetVersionTemplate(fmt.Sprintf("%s, commit %s, built at %s by %s\n", version, commit, date, builtBy))
// silence on the root cmd
rootCmd.SilenceUsage = true
rootCmd.SilenceErrors = true
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
// allow to read in from environment
viper.SetEnvPrefix("ssosync")
viper.AutomaticEnv()
appEnvVars := []string{
"google_admin",
"google_credentials",
"scim_access_token",
"scim_endpoint",
"log_level",
"log_format",
"ignore_users",
"ignore_groups",
"include_groups",
"user_match",
"group_match",
"sync_method",
}
for _, e := range appEnvVars {
if err := viper.BindEnv(e); err != nil {
log.Fatalf(errors.Wrap(err, "cannot bind environment variable").Error())
}
}
if err := viper.Unmarshal(&cfg); err != nil {
log.Fatalf(errors.Wrap(err, "cannot unmarshal config").Error())
}
// config logger
logConfig(cfg)
if cfg.IsLambda {
configLambda()
}
}
func configLambda() {
s := session.Must(session.NewSession())
svc := secretsmanager.New(s)
secrets := config.NewSecrets(svc)
unwrap, err := secrets.GoogleAdminEmail()
if err != nil {
log.Fatalf(errors.Wrap(err, "cannot read config").Error())
}
cfg.GoogleAdmin = unwrap
unwrap, err = secrets.GoogleCredentials()
if err != nil {
log.Fatalf(errors.Wrap(err, "cannot read config").Error())
}
cfg.GoogleCredentials = unwrap
unwrap, err = secrets.SCIMAccessToken()
if err != nil {
log.Fatalf(errors.Wrap(err, "cannot read config").Error())
}
cfg.SCIMAccessToken = unwrap
unwrap, err = secrets.SCIMEndpointUrl()
if err != nil {
log.Fatalf(errors.Wrap(err, "cannot read config").Error())
}
cfg.SCIMEndpoint = unwrap
}
func addFlags(cmd *cobra.Command, cfg *config.Config) {
rootCmd.PersistentFlags().StringVarP(&cfg.GoogleCredentials, "google-admin", "a", config.DefaultGoogleCredentials, "path to find credentials file for Google Workspace")
rootCmd.PersistentFlags().BoolVarP(&cfg.Debug, "debug", "d", config.DefaultDebug, "enable verbose / debug logging")
rootCmd.PersistentFlags().StringVarP(&cfg.LogFormat, "log-format", "", config.DefaultLogFormat, "log format")
rootCmd.PersistentFlags().StringVarP(&cfg.LogLevel, "log-level", "", config.DefaultLogLevel, "log level")
rootCmd.Flags().StringVarP(&cfg.SCIMAccessToken, "access-token", "t", "", "AWS SSO SCIM API Access Token")
rootCmd.Flags().StringVarP(&cfg.SCIMEndpoint, "endpoint", "e", "", "AWS SSO SCIM API Endpoint")
rootCmd.Flags().StringVarP(&cfg.GoogleCredentials, "google-credentials", "c", config.DefaultGoogleCredentials, "path to Google Workspace credentials file")
rootCmd.Flags().StringVarP(&cfg.GoogleAdmin, "google-admin", "u", "", "Google Workspace admin user email")
rootCmd.Flags().StringSliceVar(&cfg.IgnoreUsers, "ignore-users", []string{}, "ignores these Google Workspace users")
rootCmd.Flags().StringSliceVar(&cfg.IgnoreGroups, "ignore-groups", []string{}, "ignores these Google Workspace groups")
rootCmd.Flags().StringSliceVar(&cfg.IncludeGroups, "include-groups", []string{}, "include only these Google Workspace groups, NOTE: only works when --sync-method 'users_groups'")
rootCmd.Flags().StringVarP(&cfg.UserMatch, "user-match", "m", "", "Google Workspace Users filter query parameter, example: 'name:John* email:admin*', see: https://developers.google.com/admin-sdk/directory/v1/guides/search-users")
rootCmd.Flags().StringVarP(&cfg.GroupMatch, "group-match", "g", "", "Google Workspace Groups filter query parameter, example: 'name:Admin* email:aws-*', see: https://developers.google.com/admin-sdk/directory/v1/guides/search-groups")
rootCmd.Flags().StringVarP(&cfg.SyncMethod, "sync-method", "s", config.DefaultSyncMethod, "Sync method to use (users_groups|groups)")
}
func logConfig(cfg *config.Config) {
// reset log format
if cfg.LogFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
}
if cfg.Debug {
cfg.LogLevel = "debug"
}
// set the configured log level
if level, err := log.ParseLevel(cfg.LogLevel); err == nil {
log.SetLevel(level)
}
}