Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-cli/cmd/idp-gcloud-token.go
2498 views
1
// Copyright (c) 2024 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"context"
9
"encoding/json"
10
"fmt"
11
"os"
12
"path"
13
"time"
14
15
"github.com/golang-jwt/jwt/v5"
16
"github.com/spf13/cobra"
17
)
18
19
var idpGCloudTokenOpts struct {
20
Audience []string
21
}
22
23
var idpGCloudTokenCmd = &cobra.Command{
24
Use: "gcloud-token",
25
Short: "Requests a gcloud format ID token for this workspace",
26
RunE: func(cmd *cobra.Command, args []string) (err error) {
27
cmd.SilenceUsage = true
28
if len(idpGCloudTokenOpts.Audience) == 0 {
29
return fmt.Errorf("missing --audience or GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE env var")
30
}
31
ctx, cancel := context.WithTimeout(cmd.Context(), 5*time.Second)
32
defer cancel()
33
34
defer func() {
35
if err != nil {
36
out, _ := json.Marshal(map[string]any{
37
"version": 1,
38
"success": false,
39
"code": "401",
40
"message": err.Error(),
41
})
42
fmt.Print(string(out))
43
}
44
}()
45
46
tkn, err := idpToken(ctx, idpGCloudTokenOpts.Audience, "")
47
if err != nil {
48
return err
49
}
50
51
token, _, err := jwt.NewParser().ParseUnverified(tkn, jwt.MapClaims{})
52
if err != nil {
53
return err
54
}
55
56
expirationDate, err := token.Claims.GetExpirationTime()
57
if err != nil {
58
return err
59
}
60
out, err := json.Marshal(map[string]any{
61
"version": 1,
62
"success": true,
63
"token_type": "urn:ietf:params:oauth:token-type:id_token",
64
"id_token": tkn,
65
"expiration_time": expirationDate.Unix(),
66
})
67
if err != nil {
68
return err
69
}
70
fmt.Print(string(out))
71
if output := os.Getenv("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE"); output != "" {
72
err := os.MkdirAll(path.Dir(output), 0600)
73
if err != nil {
74
// omit error
75
return nil
76
}
77
// omit error
78
_ = os.WriteFile(output, out, 0600)
79
}
80
return nil
81
},
82
}
83
84
func init() {
85
idpCmd.AddCommand(idpGCloudTokenCmd)
86
audience := []string{}
87
if aud := os.Getenv("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE"); aud != "" {
88
audience = append(audience, aud)
89
}
90
idpGCloudTokenCmd.Flags().StringArrayVar(&idpGCloudTokenOpts.Audience, "audience", audience, "audience of the ID token")
91
}
92
93