1/*
2Copyright 2017 by the contributors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package main
18
19import (
20	"encoding/json"
21	"fmt"
22	"os"
23
24	"sigs.k8s.io/aws-iam-authenticator/pkg/token"
25
26	"github.com/aws/aws-sdk-go/aws/endpoints"
27	"github.com/spf13/cobra"
28	"github.com/spf13/viper"
29)
30
31var verifyCmd = &cobra.Command{
32	Use:   "verify",
33	Short: "Verify a token for debugging purpose",
34	Long:  ``,
35	Run: func(cmd *cobra.Command, args []string) {
36		tok := viper.GetString("token")
37		output := viper.GetString("output")
38		clusterID := viper.GetString("clusterID")
39		partition := viper.GetString("partition")
40
41		if tok == "" {
42			fmt.Fprintf(os.Stderr, "error: token not specified\n")
43			cmd.Usage()
44			os.Exit(1)
45		}
46
47		if clusterID == "" {
48			fmt.Fprintf(os.Stderr, "error: cluster ID not specified\n")
49			cmd.Usage()
50			os.Exit(1)
51		}
52
53		id, err := token.NewVerifier(clusterID, partition).Verify(tok)
54		if err != nil {
55			fmt.Fprintf(os.Stderr, "could not verify token: %v\n", err)
56			os.Exit(1)
57		}
58
59		if output == "json" {
60			value, err := json.MarshalIndent(id, "", "    ")
61			if err != nil {
62				fmt.Fprintf(os.Stderr, "could not unmarshal token: %v\n", err)
63			}
64			fmt.Printf("%s\n", value)
65		} else {
66			fmt.Printf("%+v\n", id)
67		}
68	},
69}
70
71func init() {
72	rootCmd.AddCommand(verifyCmd)
73	verifyCmd.Flags().StringP("token", "t", "", "Token to verify")
74	verifyCmd.Flags().StringP("output", "o", "", "Output format. Only `json` is supported currently.")
75	viper.BindPFlag("token", verifyCmd.Flags().Lookup("token"))
76	viper.BindPFlag("output", verifyCmd.Flags().Lookup("output"))
77
78	partitionKeys := []string{}
79	for _, p := range endpoints.DefaultPartitions() {
80		partitionKeys = append(partitionKeys, p.ID())
81	}
82
83	verifyCmd.Flags().String("partition",
84		endpoints.AwsPartitionID,
85		fmt.Sprintf("The AWS partition. Must be one of: %v", partitionKeys))
86	viper.BindPFlag("partition", verifyCmd.Flags().Lookup("partition"))
87
88}
89