-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassume.go
More file actions
85 lines (64 loc) · 2.1 KB
/
assume.go
File metadata and controls
85 lines (64 loc) · 2.1 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
// Copyright 2025 variHQ OÜ
// SPDX-License-Identifier: BSD-3-Clause
package main
import (
"context"
"fmt"
"log/slog"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/aws/aws-sdk-go-v2/service/sts/types"
"github.com/wakeful/trick/internal/broadcast"
)
func (a *App) assumeRole(ctx context.Context, role string) (*types.Credentials, error) {
slog.Debug("assuming role", slog.String("role", role))
assumeRole, err := a.client.AssumeRole(ctx, &sts.AssumeRoleInput{ //nolint:exhaustruct
RoleArn: aws.String(role),
RoleSessionName: aws.String("trick"),
DurationSeconds: aws.Int32(int32(a.sessionDuration.Seconds())),
})
if err != nil {
return nil, fmt.Errorf("unable to assume role, %w", err)
}
cfg, err := config.LoadDefaultConfig(ctx, config.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(
*assumeRole.Credentials.AccessKeyId,
*assumeRole.Credentials.SecretAccessKey,
*assumeRole.Credentials.SessionToken,
),
), config.WithRegion(a.region))
if err != nil {
return nil, fmt.Errorf("unable to load SDK config, %w", err)
}
slog.Debug("replacing client", slog.String("role", role))
a.client = sts.NewFromConfig(cfg)
return assumeRole.Credentials, nil
}
func (a *App) assumeNextInterestingRole(ctx context.Context) (*types.Credentials, error) {
var outputCred *types.Credentials
for {
role := a.nextRole()
slog.Info("trying to assume role", slog.String("role", role))
cred, err := a.assumeRole(ctx, role)
if err != nil {
return nil, fmt.Errorf("unable to assume role, %w", err)
}
a.broadcaster.Publish(broadcast.Message{
Chain: "main",
Role: role,
})
outputCred = cred
if len(a.usableRoles) == 0 {
slog.Debug("all roles have meaningful permissions")
break
}
if _, ok := a.usableRoles[role]; ok {
slog.Debug("found role with meaningful permissions", slog.String("role", role))
break
}
slog.Debug("role is lacking meaningful permissions", slog.String("role", role))
}
return outputCred, nil
}