-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudshell.go
More file actions
219 lines (194 loc) · 6.73 KB
/
Copy pathcloudshell.go
File metadata and controls
219 lines (194 loc) · 6.73 KB
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
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
// service is the SigV4 service name for the (unofficial) CloudShell API.
const service = "cloudshell"
// VpcConfig optionally attaches the environment to a VPC.
type VpcConfig struct {
VpcId string `json:"VpcId"`
SecurityGroupIds []string `json:"SecurityGroupIds"`
SubnetIds []string `json:"SubnetIds"`
}
// Environment is a CloudShell environment. Note: describeEnvironments returns
// only EnvironmentId; Status/VpcConfig come from getEnvironmentStatus.
type Environment struct {
EnvironmentId string `json:"EnvironmentId"`
Status string `json:"Status,omitempty"`
EnvironmentName string `json:"EnvironmentName,omitempty"`
StatusReason string `json:"StatusReason,omitempty"`
VpcConfig *VpcConfig `json:"VpcConfig,omitempty"`
}
// Client talks to the CloudShell JSON API, signing each request with SigV4.
type Client struct {
region string
creds aws.CredentialsProvider
signer *v4.Signer
http *http.Client
pollInterval time.Duration
}
// Credentials resolves the current AWS credentials (e.g. for shell injection).
func (c *Client) Credentials(ctx context.Context) (aws.Credentials, error) {
return c.creds.Retrieve(ctx)
}
// NewClient builds a Client for the given region and credential provider.
func NewClient(region string, creds aws.CredentialsProvider) *Client {
return &Client{
region: region,
creds: creds,
signer: v4.NewSigner(),
http: http.DefaultClient,
pollInterval: 2 * time.Second,
}
}
// call POSTs a SigV4-signed JSON request to the given API action and decodes the
// response into out (which may be nil, or a *json.RawMessage for the raw body).
func (c *Client) call(ctx context.Context, action string, body, out any) error {
payload, err := json.Marshal(body)
if err != nil {
return err
}
url := fmt.Sprintf("https://%s.%s.amazonaws.com/%s", service, c.region, action)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
creds, err := c.creds.Retrieve(ctx)
if err != nil {
return fmt.Errorf("resolve credentials: %w", err)
}
sum := sha256.Sum256(payload)
if err := c.signer.SignHTTP(ctx, creds, req, hex.EncodeToString(sum[:]), service, c.region, time.Now()); err != nil {
return fmt.Errorf("sign request: %w", err)
}
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode/100 != 2 {
return fmt.Errorf("%s failed (%d): %s", action, resp.StatusCode, string(data))
}
if out != nil && len(data) > 0 {
return json.Unmarshal(data, out)
}
return nil
}
// DescribeEnvironments lists environments. The response shape varies, so it is
// coerced defensively (wrapped object, bare array, or single object).
func (c *Client) DescribeEnvironments(ctx context.Context) ([]Environment, error) {
var raw json.RawMessage
if err := c.call(ctx, "describeEnvironments", map[string]any{}, &raw); err != nil {
return nil, err
}
var wrapped struct {
Environments []Environment `json:"Environments"`
}
if json.Unmarshal(raw, &wrapped) == nil && wrapped.Environments != nil {
return wrapped.Environments, nil
}
var arr []Environment
if json.Unmarshal(raw, &arr) == nil {
return arr, nil
}
var single Environment
if json.Unmarshal(raw, &single) == nil && single.EnvironmentId != "" {
return []Environment{single}, nil
}
return nil, nil
}
// DescribeEnvironmentsWithStatus enriches each environment with its real status
// (describeEnvironments returns only the id). Environments that can't be resolved
// — e.g. lingering after deletion — are marked DELETED.
func (c *Client) DescribeEnvironmentsWithStatus(ctx context.Context) ([]Environment, error) {
envs, err := c.DescribeEnvironments(ctx)
if err != nil {
return nil, err
}
for i := range envs {
s, err := c.GetEnvironmentStatus(ctx, envs[i].EnvironmentId)
if err != nil {
envs[i].Status = "DELETED"
continue
}
envs[i].Status = s.Status
envs[i].VpcConfig = s.VpcConfig
if s.EnvironmentName != "" {
envs[i].EnvironmentName = s.EnvironmentName
}
}
return envs, nil
}
// GetEnvironmentStatus returns the current status (and VpcConfig) of an environment.
func (c *Client) GetEnvironmentStatus(ctx context.Context, id string) (*Environment, error) {
var e Environment
err := c.call(ctx, "getEnvironmentStatus", map[string]string{"EnvironmentId": id}, &e)
return &e, err
}
// CreateEnvironment creates an environment, optionally attached to a VPC. When an
// environment already exists, CloudShell returns the existing one (idempotent).
func (c *Client) CreateEnvironment(ctx context.Context, vpc *VpcConfig) (*Environment, error) {
body := map[string]any{}
if vpc != nil {
body["EnvironmentName"] = envName
body["VpcConfig"] = vpc
}
var e Environment
err := c.call(ctx, "createEnvironment", body, &e)
return &e, err
}
// StartEnvironment resumes a suspended environment.
func (c *Client) StartEnvironment(ctx context.Context, id string) error {
return c.call(ctx, "startEnvironment", map[string]string{"EnvironmentId": id}, nil)
}
// CreateSession returns the raw session payload to hand to session-manager-plugin.
func (c *Client) CreateSession(ctx context.Context, id string) (json.RawMessage, error) {
var raw json.RawMessage
err := c.call(ctx, "createSession", map[string]string{"EnvironmentId": id}, &raw)
return raw, err
}
// DeleteEnvironment permanently deletes an environment and its persistent storage.
func (c *Client) DeleteEnvironment(ctx context.Context, id string) error {
return c.call(ctx, "deleteEnvironment", map[string]string{"EnvironmentId": id}, nil)
}
// WaitForRunning drives an environment to RUNNING: it resumes a suspended one
// (once), waits through CREATING/RESUMING, and fails on deletion or timeout.
func (c *Client) WaitForRunning(ctx context.Context, id, initial string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
status := initial
startIssued := false
for {
switch status {
case "RUNNING":
return nil
case "DELETING", "DELETED":
return fmt.Errorf("environment is %s; cannot connect", status)
case "SUSPENDED", "SUSPENDING":
if !startIssued {
_ = c.StartEnvironment(ctx, id)
startIssued = true
}
default:
startIssued = false
}
if time.Now().After(deadline) {
return fmt.Errorf("timed out waiting for environment to become available")
}
time.Sleep(c.pollInterval)
if e, err := c.GetEnvironmentStatus(ctx, id); err == nil {
status = e.Status
}
}
}