|
1 | | -// Copyright 2023 Terramate GmbH |
| 1 | +// Copyright 2024 Terramate GmbH |
2 | 2 | // SPDX-License-Identifier: MPL-2.0 |
3 | 3 |
|
4 | 4 | package cli |
5 | 5 |
|
6 | 6 | import ( |
7 | | - "context" |
8 | 7 | "fmt" |
9 | | - "math" |
10 | 8 | "net/url" |
11 | 9 | "os" |
12 | | - "sync" |
| 10 | + "strconv" |
13 | 11 | "time" |
14 | 12 |
|
15 | | - "github.com/golang-jwt/jwt" |
16 | | - "github.com/terramate-io/terramate/cloud" |
| 13 | + "github.com/terramate-io/terramate/cmd/terramate/cli/cliconfig" |
17 | 14 | "github.com/terramate-io/terramate/cmd/terramate/cli/github" |
18 | 15 | "github.com/terramate-io/terramate/cmd/terramate/cli/out" |
19 | 16 | "github.com/terramate-io/terramate/errors" |
20 | 17 | "github.com/terramate-io/terramate/printer" |
21 | 18 | ) |
22 | 19 |
|
23 | | -const githubOIDCProviderName = "GitHub Actions OIDC" |
| 20 | +const defaultGitHubClientID = "08e1f8d6f599c7ec48c5" |
24 | 21 |
|
25 | | -type githubOIDC struct { |
26 | | - mu sync.RWMutex |
27 | | - token string |
28 | | - jwtClaims jwt.MapClaims |
29 | | - |
30 | | - expireAt time.Time |
31 | | - repoOwner string |
32 | | - repoName string |
33 | | - |
34 | | - reqURL string |
35 | | - reqToken string |
36 | | - orgs cloud.MemberOrganizations |
37 | | - |
38 | | - output out.O |
39 | | - client *cloud.Client |
40 | | -} |
41 | | - |
42 | | -func newGithubOIDC(output out.O, client *cloud.Client) *githubOIDC { |
43 | | - return &githubOIDC{ |
44 | | - output: output, |
45 | | - client: client, |
| 22 | +func githubLogin(output out.O, tmcBaseURL string, idpKey string, clicfg cliconfig.Config) (string, []string, error) { |
| 23 | + token, err := githubAuth() |
| 24 | + if err != nil { |
| 25 | + return "", nil, err |
46 | 26 | } |
47 | | -} |
48 | 27 |
|
49 | | -func (g *githubOIDC) Load() (bool, error) { |
50 | | - const envReqURL = "ACTIONS_ID_TOKEN_REQUEST_URL" |
51 | | - const envReqTok = "ACTIONS_ID_TOKEN_REQUEST_TOKEN" |
52 | | - |
53 | | - g.reqURL = os.Getenv(envReqURL) |
54 | | - if g.reqURL == "" { |
55 | | - return false, nil |
| 28 | + postBody := url.Values{ |
| 29 | + "access_token": []string{token}, |
| 30 | + "providerId": []string{"github.com"}, |
56 | 31 | } |
57 | 32 |
|
58 | | - g.reqToken = os.Getenv(envReqTok) |
59 | | - |
60 | | - audience := oidcAudience() |
61 | | - if audience != "" { |
62 | | - u, err := url.Parse(g.reqURL) |
63 | | - if err != nil { |
64 | | - return false, errors.E(err, "invalid ACTIONS_ID_TOKEN_REQUEST_URL env var") |
65 | | - } |
66 | | - |
67 | | - qr := u.Query() |
68 | | - qr.Set("audience", audience) |
69 | | - u.RawQuery = qr.Encode() |
70 | | - g.reqURL = u.String() |
| 33 | + reqPayload := googleSignInPayload{ |
| 34 | + PostBody: postBody.Encode(), |
| 35 | + RequestURI: tmcBaseURL + "/__/auth/handler", |
| 36 | + ReturnIdpCredential: true, |
| 37 | + ReturnSecureToken: true, |
71 | 38 | } |
72 | 39 |
|
73 | | - err := g.Refresh() |
| 40 | + cred, email, alreadyUsedProviders, err := signInWithIDP(reqPayload, idpKey) |
74 | 41 | if err != nil { |
75 | | - return false, err |
| 42 | + return email, alreadyUsedProviders, err |
76 | 43 | } |
77 | | - g.client.Credential = g |
78 | | - return true, g.fetchDetails() |
79 | | -} |
80 | 44 |
|
81 | | -func (g *githubOIDC) Name() string { |
82 | | - return githubOIDCProviderName |
| 45 | + output.MsgStdOut("Logged in as %s", cred.UserDisplayName()) |
| 46 | + output.MsgStdOutV("Token: %s", cred.IDToken) |
| 47 | + expire, _ := strconv.Atoi(cred.ExpiresIn) |
| 48 | + output.MsgStdOutV("Expire at: %s", time.Now().Add(time.Second*time.Duration(expire)).Format(time.RFC822Z)) |
| 49 | + return email, nil, saveCredential(output, cred, clicfg) |
83 | 50 | } |
84 | 51 |
|
85 | | -func (g *githubOIDC) IsExpired() bool { |
86 | | - g.mu.RLock() |
87 | | - defer g.mu.RUnlock() |
88 | | - return time.Now().After(g.expireAt) |
89 | | -} |
90 | | - |
91 | | -func (g *githubOIDC) ExpireAt() time.Time { |
92 | | - g.mu.RLock() |
93 | | - defer g.mu.RUnlock() |
94 | | - return g.expireAt |
95 | | -} |
96 | | - |
97 | | -func (g *githubOIDC) Refresh() (err error) { |
98 | | - if g.token != "" { |
99 | | - g.output.MsgStdOutV("refreshing token...") |
100 | | - |
101 | | - defer func() { |
102 | | - if err == nil { |
103 | | - g.output.MsgStdOutV("token successfully refreshed.") |
104 | | - g.output.MsgStdOutV("next token refresh in: %s", time.Until(g.ExpireAt())) |
105 | | - } |
106 | | - }() |
107 | | - } |
108 | | - |
109 | | - ctx, cancel := context.WithTimeout(context.Background(), defaultGithubTimeout) |
110 | | - defer cancel() |
111 | | - |
112 | | - token, err := github.OIDCToken(ctx, github.OIDCVars{ |
113 | | - ReqURL: g.reqURL, |
114 | | - ReqToken: g.reqToken, |
115 | | - }) |
116 | | - |
| 52 | +func githubAuth() (string, error) { |
| 53 | + oauthCtx, err := github.OAuthDeviceFlowAuthStart(ghClientID()) |
117 | 54 | if err != nil { |
118 | | - return errors.E(err, "requesting new Github OIDC token") |
| 55 | + return "", err |
119 | 56 | } |
120 | 57 |
|
121 | | - g.mu.Lock() |
122 | | - defer g.mu.Unlock() |
123 | | - |
124 | | - g.token = token |
125 | | - g.jwtClaims, err = tokenClaims(g.token) |
126 | | - if err != nil { |
127 | | - return err |
128 | | - } |
129 | | - exp, ok := g.jwtClaims["exp"].(float64) |
130 | | - if !ok { |
131 | | - return errors.E(`cached JWT token has no "exp" field`) |
132 | | - } |
133 | | - sec, dec := math.Modf(exp) |
134 | | - g.expireAt = time.Unix(int64(sec), int64(dec*(1e9))) |
| 58 | + printer.Stdout.Println(fmt.Sprintf("Please visit: %s", oauthCtx.VerificationURI)) |
| 59 | + printer.Stdout.Println(fmt.Sprintf("and enter code: %s", oauthCtx.UserCode)) |
135 | 60 |
|
136 | | - repoOwner, ok := g.jwtClaims["repository_owner"].(string) |
137 | | - if !ok { |
138 | | - return errors.E(`GitHub OIDC JWT with no "repository_owner" payload field.`) |
139 | | - } |
140 | | - repoName, ok := g.jwtClaims["repository"].(string) |
141 | | - if !ok { |
142 | | - return errors.E(`GitHub OIDC JWT with no "repository" payload field.`) |
143 | | - } |
144 | | - g.repoOwner = repoOwner |
145 | | - g.repoName = repoName |
146 | | - return nil |
147 | | -} |
| 61 | + for { |
| 62 | + var token string |
| 63 | + token, err = oauthCtx.ProbeAuthState() |
| 64 | + if err == nil { |
| 65 | + return token, nil |
| 66 | + } |
148 | 67 |
|
149 | | -func (g *githubOIDC) Claims() jwt.MapClaims { |
150 | | - g.mu.RLock() |
151 | | - defer g.mu.RUnlock() |
152 | | - return g.jwtClaims |
153 | | -} |
| 68 | + var errInfo *errors.Error |
| 69 | + if !errors.As(err, &errInfo) { |
| 70 | + return "", err // unexpected err |
| 71 | + } |
154 | 72 |
|
155 | | -func (g *githubOIDC) DisplayClaims() []keyValue { |
156 | | - return []keyValue{ |
157 | | - { |
158 | | - key: "owner", |
159 | | - value: g.repoOwner, |
160 | | - }, |
161 | | - { |
162 | | - key: "repository", |
163 | | - value: g.repoName, |
164 | | - }, |
165 | | - } |
166 | | -} |
| 73 | + interval := time.Duration(oauthCtx.Interval) * time.Second |
167 | 74 |
|
168 | | -func (g *githubOIDC) Token() (string, error) { |
169 | | - if g.IsExpired() { |
170 | | - err := g.Refresh() |
171 | | - if err != nil { |
| 75 | + switch errInfo.Kind { |
| 76 | + case github.ErrDeviceFlowSlowDown: |
| 77 | + interval += 5 * time.Second |
| 78 | + fallthrough |
| 79 | + case github.ErrDeviceFlowAuthPending: |
| 80 | + time.Sleep(interval) |
| 81 | + default: |
172 | 82 | return "", err |
173 | 83 | } |
174 | 84 | } |
175 | | - g.mu.RLock() |
176 | | - defer g.mu.RUnlock() |
177 | | - return g.token, nil |
178 | | -} |
179 | | - |
180 | | -// Validate if the credential is ready to be used. |
181 | | -func (g *githubOIDC) fetchDetails() error { |
182 | | - const apiTimeout = 5 * time.Second |
183 | | - |
184 | | - ctx, cancel := context.WithTimeout(context.Background(), apiTimeout) |
185 | | - defer cancel() |
186 | | - orgs, err := g.client.MemberOrganizations(ctx) |
187 | | - if err != nil { |
188 | | - return err |
189 | | - } |
190 | | - g.orgs = orgs |
191 | | - return nil |
192 | 85 | } |
193 | 86 |
|
194 | | -func (g *githubOIDC) info(selectedOrgName string) { |
195 | | - if len(g.orgs) > 0 && g.orgs[0].Status == "trusted" { |
196 | | - printer.Stdout.Println("status: signed in") |
197 | | - } else { |
198 | | - printer.Stdout.Println("status: untrusted") |
199 | | - } |
200 | | - |
201 | | - printer.Stdout.Println(fmt.Sprintf("provider: %s", g.Name())) |
202 | | - |
203 | | - for _, kv := range g.DisplayClaims() { |
204 | | - printer.Stdout.Println(fmt.Sprintf("%s: %s", kv.key, kv.value)) |
205 | | - } |
206 | | - |
207 | | - if len(g.orgs) > 0 { |
208 | | - printer.Stdout.Println(fmt.Sprintf("organizations: %s", g.orgs)) |
| 87 | +func ghClientID() string { |
| 88 | + idpKey := os.Getenv("TMC_API_GITHUB_CLIENT_ID") |
| 89 | + if idpKey == "" { |
| 90 | + idpKey = defaultGitHubClientID |
209 | 91 | } |
210 | | - |
211 | | - if selectedOrgName == "" && len(g.orgs) > 1 { |
212 | | - printer.Stderr.Warn("User is member of multiple organizations but none was selected") |
213 | | - } |
214 | | - |
215 | | - if len(g.orgs) == 0 { |
216 | | - printer.Stderr.Warn("You are not part of an organization. Please visit cloud.terramate.io to create an organization.") |
217 | | - } |
218 | | -} |
219 | | - |
220 | | -func (g *githubOIDC) organizations() cloud.MemberOrganizations { |
221 | | - return g.orgs |
| 92 | + return idpKey |
222 | 93 | } |
0 commit comments