Skip to content

Commit 265f147

Browse files
committed
move GH requester to SDK
Signed-off-by: Jorge Turrado <[email protected]>
1 parent 60c10fb commit 265f147

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

core/oidcadapters/githubactions.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package oidcadapters
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"io"
8+
"net/http"
9+
"net/url"
10+
)
11+
12+
func RequestGHOIDCToken(oidc_request_url, oidc_request_token string) OIDCTokenFunc {
13+
return func(ctx context.Context) (string, error) {
14+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, oidc_request_url, http.NoBody)
15+
if err != nil {
16+
return "", fmt.Errorf("githubAssertion: failed to build request: %w", err)
17+
}
18+
19+
query, err := url.ParseQuery(req.URL.RawQuery)
20+
if err != nil {
21+
return "", fmt.Errorf("githubAssertion: cannot parse URL query")
22+
}
23+
24+
if query.Get("audience") == "" {
25+
query.Set("audience", "sts.accounts.stackit.cloud")
26+
req.URL.RawQuery = query.Encode()
27+
}
28+
29+
req.Header.Set("Accept", "application/json")
30+
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oidc_request_token))
31+
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
32+
33+
resp, err := http.DefaultClient.Do(req)
34+
if err != nil {
35+
return "", fmt.Errorf("githubAssertion: cannot request token: %w", err)
36+
}
37+
38+
defer func() {
39+
_ = resp.Body.Close()
40+
}()
41+
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
42+
if err != nil {
43+
return "", fmt.Errorf("githubAssertion: cannot parse response: %w", err)
44+
}
45+
46+
if c := resp.StatusCode; c < 200 || c > 299 {
47+
return "", fmt.Errorf("githubAssertion: received HTTP status %d with response: %s", resp.StatusCode, body)
48+
}
49+
50+
var tokenRes struct {
51+
Value string `json:"value"`
52+
}
53+
if err := json.Unmarshal(body, &tokenRes); err != nil {
54+
return "", fmt.Errorf("githubAssertion: cannot unmarshal response: %w", err)
55+
}
56+
57+
return tokenRes.Value, nil
58+
}
59+
}

0 commit comments

Comments
 (0)