Repository navigation
Expand file tree
/
Copy pathdiscord.go
More file actions
253 lines (243 loc) · 9.33 KB
/
Copy pathdiscord.go
File metadata and controls
253 lines (243 loc) · 9.33 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/bwmarrin/discordgo"
discordbackend "github.com/thirdscam/chatanium-flexmodule/internal/backend/discord"
discordhttp "github.com/thirdscam/chatanium-flexmodule/internal/backend/discord/http"
runtime "github.com/thirdscam/chatanium-flexmodule/internal/runtime"
"github.com/thirdscam/chatanium-flexmodule/internal/runtime/upload"
wire "github.com/thirdscam/chatanium-flexmodule/proto/core-v2"
"google.golang.org/protobuf/proto"
)
type discordOperatorConfig struct {
ApplicationID string `json:"application_id"`
BotUserID string `json:"bot_user_id"`
OwnershipDirectory string `json:"ownership_directory"`
Intents discordgo.Intent `json:"intents"`
GatewayFrameMaxBytes int64 `json:"gateway_frame_max_bytes"`
GatewayDecodedMaxBytes int64 `json:"gateway_decoded_max_bytes"`
CredentialTTL runtime.Duration `json:"credential_ttl"`
InteractionTTL runtime.Duration `json:"interaction_ttl"`
NonceTTL runtime.Duration `json:"nonce_ttl"`
NoncesPerInstance int `json:"nonces_per_instance"`
NoncesPerHost int `json:"nonces_per_host"`
NonceChunksMax int `json:"nonce_chunks_max"`
RoutesPerModule int `json:"routes_per_module"`
RoutesPerHost int `json:"routes_per_host"`
MaxRoutesPerRequest int `json:"max_routes_per_request"`
MaxFilesPerRequest int `json:"max_files_per_request"`
FileMaxBytes int64 `json:"file_max_bytes"`
RequestMaxBytes int64 `json:"request_max_bytes"`
PresenceOwner runtime.ModuleID `json:"presence_owner"`
HTTP struct {
RequestDeadline runtime.Duration `json:"request_deadline"`
JSONMaxBytes int64 `json:"json_max_bytes"`
ResponseMaxBytes int64 `json:"response_max_bytes"`
HeaderMaxBytes int64 `json:"header_max_bytes"`
RequestsPerInstance int `json:"requests_per_instance"`
RequestsPerHost int `json:"requests_per_host"`
RateLimitBuckets int `json:"rate_limit_buckets"`
RateLimitRetention runtime.Duration `json:"rate_limit_retention"`
} `json:"http"`
ProvisionedSecrets map[string]struct {
ModuleID runtime.ModuleID `json:"module_id"`
Purpose string `json:"purpose"`
Resource *wire.ResourceSelector `json:"resource"`
ExpiresAt time.Time `json:"expires_at"`
} `json:"provisioned_secrets"`
Voice json.RawMessage `json:"voice"`
}
var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
func hostSecret(source string) (string, error) {
if !strings.HasPrefix(source, "env:") || !envName.MatchString(strings.TrimPrefix(source, "env:")) {
return "", errors.New("secret source must be an explicit environment binding")
}
value, ok := os.LookupEnv(strings.TrimPrefix(source, "env:"))
if !ok || value == "" || strings.ContainsAny(value, "\r\n\x00") {
return "", errors.New("required host secret binding unavailable")
}
return value, nil
}
func newDiscordBackend(ctx context.Context, config runtime.Config, backend runtime.BackendConfig, files *upload.UploadStore, onError func(error)) (*discordbackend.Backend, error) {
var c discordOperatorConfig
if strictJSON(backend.Config, &c) != nil {
return nil, errors.New("invalid Discord operator configuration")
}
if !isolatedHostDirectory(c.OwnershipDirectory, config.Host.StorageRoot, config.Host.IPCRoot) {
return nil, errors.New("Discord ownership directory must be private and outside module mounts")
}
if len(backend.SecretSources) != len(c.ProvisionedSecrets)+1 {
return nil, errors.New("unexpected Discord secret bindings")
}
token, err := hostSecret(backend.SecretSources["bot_token"])
if err != nil {
return nil, err
}
token = strings.TrimPrefix(token, "Bot ")
if token == "" {
return nil, errors.New("required host bot credential unavailable")
}
secrets := make(map[string]discordbackend.Secret, len(c.ProvisionedSecrets))
values := []string{token}
for id, metadata := range c.ProvisionedSecrets {
if id == "bot_token" {
return nil, errors.New("bot credential cannot be provisioned to modules")
}
value, e := hostSecret(backend.SecretSources[id])
if e != nil {
return nil, e
}
values = append(values, value)
secrets[id] = discordbackend.Secret{Value: value, ModuleID: metadata.ModuleID, Purpose: metadata.Purpose, Resource: metadata.Resource, ExpiresAt: metadata.ExpiresAt}
}
// Known host credentials must never be smuggled through module JSON, argv or
// public installation identities. The manager separately excludes host env.
for _, spec := range config.Modules {
if containsSecretJSON(spec.Config.Json, values) {
return nil, errors.New("host secret found in module configuration")
}
fields := [4]string{string(spec.ModuleID), spec.ImageDigest, spec.ConfigRevision, spec.ApprovalRevision}
for _, group := range [][]string{fields[:], spec.Entrypoint, spec.Args} {
for _, field := range group {
for _, value := range values {
if strings.Contains(field, value) {
return nil, errors.New("host secret found in module installation data")
}
}
}
}
for _, binding := range spec.CredentialBindings {
if binding.BackendID != "discord" {
continue
}
secret, ok := secrets[binding.SecretID]
if !ok || secret.ModuleID != spec.ModuleID || secret.Purpose != binding.Purpose || !proto.Equal(secret.Resource, binding.Resource) {
return nil, errors.New("invalid provisioned credential binding")
}
}
}
h := c.HTTP
b, err := discordbackend.New(ctx, discordbackend.Config{BotToken: token, ApplicationID: c.ApplicationID, BotUserID: c.BotUserID, OwnershipDirectory: c.OwnershipDirectory, Intents: c.Intents, GatewayFrameMaxBytes: c.GatewayFrameMaxBytes, GatewayDecodedMaxBytes: c.GatewayDecodedMaxBytes, CredentialTTL: time.Duration(c.CredentialTTL), InteractionTTL: time.Duration(c.InteractionTTL), NonceTTL: time.Duration(c.NonceTTL), NoncesPerInstance: c.NoncesPerInstance, NoncesPerHost: c.NoncesPerHost, NonceChunksMax: c.NonceChunksMax, RoutesPerModule: c.RoutesPerModule, RoutesPerHost: c.RoutesPerHost, MaxRoutesPerRequest: c.MaxRoutesPerRequest, MaxFilesPerRequest: c.MaxFilesPerRequest, FileMaxBytes: c.FileMaxBytes, RequestMaxBytes: c.RequestMaxBytes, PresenceOwner: c.PresenceOwner, Secrets: secrets, Uploads: files, OnError: onError, HTTP: discordhttp.Config{RequestDeadline: time.Duration(h.RequestDeadline), JSONMaxBytes: h.JSONMaxBytes, ResponseMaxBytes: h.ResponseMaxBytes, HeaderMaxBytes: h.HeaderMaxBytes, RequestsPerInstance: h.RequestsPerInstance, RequestsPerHost: h.RequestsPerHost, RateLimitBuckets: h.RateLimitBuckets, RateLimitRetention: time.Duration(h.RateLimitRetention)}})
if err != nil {
return nil, errors.New("Discord backend initialization failed")
}
if err = attachVoice(ctx, b, c.Voice, config.Limits.ControlMessageMaxBytes); err != nil {
if b.Close() != nil {
return nil, errors.Join(err, errors.New("Discord backend cleanup failed"))
}
return nil, err
}
return b, nil
}
func strictJSON(raw []byte, out any) error {
if rejectDuplicateJSON(raw) != nil {
return errors.New("invalid JSON document")
}
d := json.NewDecoder(bytes.NewReader(raw))
d.DisallowUnknownFields()
if d.Decode(out) != nil || d.Decode(new(any)) != io.EOF {
return errors.New("invalid JSON document")
}
return nil
}
func rejectDuplicateJSON(raw []byte) error {
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
var scan func() error
scan = func() error {
t, e := d.Token()
if e != nil {
return e
}
del, ok := t.(json.Delim)
if !ok {
return nil
}
switch del {
case '{':
seen := map[string]bool{}
for d.More() {
key, e := d.Token()
if e != nil {
return e
}
s, ok := key.(string)
if !ok || seen[s] {
return errors.New("duplicate JSON field")
}
seen[s] = true
if e = scan(); e != nil {
return e
}
}
case '[':
for d.More() {
if e = scan(); e != nil {
return e
}
}
default:
return errors.New("invalid JSON delimiter")
}
_, e = d.Token()
return e
}
if e := scan(); e != nil {
return e
}
if _, e := d.Token(); e != io.EOF {
return errors.New("trailing JSON")
}
return nil
}
func containsSecretJSON(raw []byte, secrets []string) bool {
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
for {
token, err := d.Token()
if err == io.EOF {
return false
}
if err != nil {
return true
}
if text, ok := token.(string); ok {
for _, secret := range secrets {
if strings.Contains(text, secret) {
return true
}
}
}
}
}
func isolatedHostDirectory(path string, mounts ...string) bool {
if !canonicalPath(path) {
return false
}
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return false
}
for _, mount := range mounts {
actual, err := filepath.EvalSymlinks(mount)
if err != nil {
return false
}
for _, pair := range [][2]string{{mount, path}, {actual, resolved}} {
relative, err := filepath.Rel(pair[0], pair[1])
if err != nil || relative == "." || relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return false
}
}
}
return true
}