-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
490 lines (435 loc) · 12.4 KB
/
Copy pathconfig.go
File metadata and controls
490 lines (435 loc) · 12.4 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
const (
configFile = "config.json"
sessionFile = "session.json"
activeSessionWindowSeconds = 12 * 60 * 60
)
type LocalConfig struct {
Version int `json:"version"`
Project ProjectConfig `json:"project"`
ComputeKey ComputeKeyConfig `json:"compute_key"`
Provider ProviderConfig `json:"provider"`
Target TargetConfig `json:"target"`
}
type ProjectConfig struct {
FullName string `json:"full_name"`
ID *string `json:"id,omitempty"`
}
type ComputeKeyConfig struct {
ID string `json:"id"`
}
type ProviderConfig struct {
Name string `json:"name"`
KeyHash *string `json:"key_hash,omitempty"`
CredentialStorage string `json:"credential_storage"`
}
type TargetConfig struct {
Name string `json:"name"`
}
type LocalSession struct {
Version int `json:"version"`
ID string `json:"id"`
RepoRoot string `json:"repo_root"`
ProjectFullName string `json:"project_full_name"`
ProjectID *string `json:"project_id,omitempty"`
ComputeKeyID string `json:"compute_key_id"`
Target string `json:"target"`
StartedAtUnix uint64 `json:"started_at_unix"`
UpdatedAtUnix uint64 `json:"updated_at_unix"`
FinishedAtUnix *uint64 `json:"finished_at_unix,omitempty"`
LaunchProofHash *string `json:"launch_proof_hash,omitempty"`
LaunchProofToken string `json:"-"`
}
type RepoPaths struct {
Root string
RepoStateDir string
StateDir string
Config string
Session string
GithubOrigin string
}
func discoverRepoPaths(target string) (*RepoPaths, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("read current directory: %w", err)
}
return repoPathsFromRoot(cwd, target)
}
func discoverRepoPathsConfigured(target string) (*RepoPaths, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("read current directory: %w", err)
}
return repoPathsFromRootConfigured(cwd, target)
}
func repoPathsFromRoot(start, target string) (*RepoPaths, error) {
root, err := findRepoRoot(start)
if err != nil {
return nil, err
}
root, err = filepath.EvalSymlinks(root)
if err != nil {
return nil, fmt.Errorf("canonicalize %s: %w", root, err)
}
gp, err := gitPaths(root)
if err != nil {
return nil, err
}
origin, err := readGitOrigin(gp)
if err != nil {
return nil, err
}
if origin == "" {
return nil, errors.New("could not verify opub project: git origin is not configured")
}
stateRoot, err := userStateRoot()
if err != nil {
return nil, err
}
project := parseGithubRemoteProject(origin)
if project == "" {
return nil, fmt.Errorf("could not verify opub project against git origin %q", origin)
}
repoStateDir := filepath.Join(stateRoot, "repos", stateKey(root, project))
stateDir := filepath.Join(repoStateDir, "targets", target)
return &RepoPaths{
Root: root,
RepoStateDir: repoStateDir,
StateDir: stateDir,
Config: filepath.Join(stateDir, configFile),
Session: filepath.Join(stateDir, sessionFile),
GithubOrigin: origin,
}, nil
}
func repoPathsFromRootConfigured(start, target string) (*RepoPaths, error) {
if target != "" {
return repoPathsFromRoot(start, target)
}
if t := os.Getenv("OPUB_TARGET"); t != "" {
return repoPathsFromRoot(start, t)
}
probe, err := repoPathsFromRoot(start, "_probe")
if err != nil {
return nil, err
}
targetsDir := filepath.Join(probe.RepoStateDir, "targets")
entries, err := os.ReadDir(targetsDir)
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("no opub target config found under %s", targetsDir)
}
if err != nil {
return nil, fmt.Errorf("read %s: %w", targetsDir, err)
}
var configured []string
for _, e := range entries {
if e.IsDir() {
candidate := filepath.Join(targetsDir, e.Name(), configFile)
if _, err := os.Stat(candidate); err == nil {
configured = append(configured, e.Name())
}
}
}
switch len(configured) {
case 1:
return repoPathsFromRoot(start, configured[0])
case 0:
return nil, fmt.Errorf("no opub target config found under %s", targetsDir)
default:
return nil, fmt.Errorf("multiple opub target configs found (%s); pass --target or start MCP through `opub run <target>`", strings.Join(configured, ", "))
}
}
func readConfig(paths *RepoPaths) (*LocalConfig, error) {
data, err := os.ReadFile(paths.Config)
if err != nil {
return nil, fmt.Errorf("read %s: %w", paths.Config, err)
}
var cfg LocalConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse %s: %w", paths.Config, err)
}
return &cfg, nil
}
func writeConfig(paths *RepoPaths, cfg *LocalConfig) error {
if err := os.MkdirAll(paths.StateDir, 0755); err != nil {
return fmt.Errorf("create %s: %w", paths.StateDir, err)
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("serialize opub config: %w", err)
}
if err := os.WriteFile(paths.Config, append(data, '\n'), 0600); err != nil {
return fmt.Errorf("write %s: %w", paths.Config, err)
}
return nil
}
func readSession(paths *RepoPaths) (*LocalSession, error) {
data, err := os.ReadFile(paths.Session)
if err != nil {
return nil, fmt.Errorf("read %s: %w", paths.Session, err)
}
var s LocalSession
if err := json.Unmarshal(data, &s); err != nil {
return nil, fmt.Errorf("parse %s: %w", paths.Session, err)
}
return &s, nil
}
func writeSession(paths *RepoPaths, cfg *LocalConfig) (*LocalSession, error) {
if err := os.MkdirAll(paths.StateDir, 0755); err != nil {
return nil, fmt.Errorf("create %s: %w", paths.StateDir, err)
}
now := unixNow()
launchProofToken, launchProofHash, err := newLaunchProof()
if err != nil {
return nil, err
}
existing, err := readSession(paths)
if err != nil && !errors.Is(err, os.ErrNotExist) {
// unwrap to check the underlying cause
var pathErr *os.PathError
if !errors.As(err, &pathErr) {
return nil, err
}
}
var reusable *LocalSession
if existing != nil &&
existing.ProjectFullName == cfg.Project.FullName &&
existing.ComputeKeyID == cfg.ComputeKey.ID &&
existing.Target == cfg.Target.Name &&
existing.FinishedAtUnix == nil &&
now-existing.UpdatedAtUnix <= activeSessionWindowSeconds {
reusable = existing
}
id := fmt.Sprintf("local-%d-%d", now, os.Getpid())
if reusable != nil {
id = reusable.ID
}
var startedAt uint64 = now
if reusable != nil {
startedAt = reusable.StartedAtUnix
}
session := &LocalSession{
Version: 1,
ID: id,
RepoRoot: paths.Root,
ProjectFullName: cfg.Project.FullName,
ProjectID: cfg.Project.ID,
ComputeKeyID: cfg.ComputeKey.ID,
Target: cfg.Target.Name,
StartedAtUnix: startedAt,
UpdatedAtUnix: now,
LaunchProofHash: &launchProofHash,
LaunchProofToken: launchProofToken,
}
data, err := json.MarshalIndent(session, "", " ")
if err != nil {
return nil, fmt.Errorf("serialize opub session: %w", err)
}
if err := os.WriteFile(paths.Session, append(data, '\n'), 0600); err != nil {
return nil, fmt.Errorf("write %s: %w", paths.Session, err)
}
return session, nil
}
func newLaunchProof() (token string, hash string, err error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", "", fmt.Errorf("generate launch proof: %w", err)
}
token = base64.RawURLEncoding.EncodeToString(b)
return token, hashLaunchProofToken(token), nil
}
func hashLaunchProofToken(token string) string {
sum := sha256.Sum256([]byte(token))
return fmt.Sprintf("%x", sum[:])
}
func persistSession(paths *RepoPaths, session *LocalSession) error {
data, err := json.MarshalIndent(session, "", " ")
if err != nil {
return fmt.Errorf("serialize opub session: %w", err)
}
if err := os.WriteFile(paths.Session, append(data, '\n'), 0600); err != nil {
return fmt.Errorf("write %s: %w", paths.Session, err)
}
return nil
}
func userStateRoot() (string, error) {
if v := os.Getenv("OPUB_HOME"); v != "" {
return v, nil
}
if v := os.Getenv("XDG_STATE_HOME"); v != "" {
return filepath.Join(v, "opub"), nil
}
home := os.Getenv("HOME")
if home == "" {
return "", errors.New("OPUB_HOME, XDG_STATE_HOME, or HOME must be set for opub user state")
}
return filepath.Join(home, ".local", "state", "opub"), nil
}
func validateProjectName(name string) error {
parts := strings.SplitN(name, "/", 3)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return errors.New("project must be in owner/repo format")
}
return nil
}
func verifyProjectMatchesOrigin(paths *RepoPaths, project string) error {
origin := parseGithubRemoteProject(paths.GithubOrigin)
if origin == "" {
return fmt.Errorf("could not verify opub project against git origin %q", paths.GithubOrigin)
}
if project != origin {
return fmt.Errorf("opub project %q does not match git origin %q", project, origin)
}
return nil
}
func parseGithubRemoteProject(originURL string) string {
s := strings.TrimSpace(originURL)
for _, prefix := range []string{
"git@github.com:",
"https://github.com/",
"http://github.com/",
"ssh://git@github.com/",
} {
if after, ok := strings.CutPrefix(s, prefix); ok {
s = after
break
}
}
s = strings.TrimSuffix(s, ".git")
parts := strings.Split(s, "/")
if len(parts) != 2 || strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" {
return ""
}
return strings.TrimSpace(parts[0]) + "/" + strings.TrimSpace(parts[1])
}
type gitPathsResult struct {
gitDir string
commonDir string
}
func gitPaths(root string) (*gitPathsResult, error) {
dotGit := filepath.Join(root, ".git")
info, err := os.Stat(dotGit)
if err != nil {
return nil, fmt.Errorf("stat %s: %w", dotGit, err)
}
var gitDir string
if info.IsDir() {
gitDir = dotGit
} else {
body, err := os.ReadFile(dotGit)
if err != nil {
return nil, fmt.Errorf("read %s: %w", dotGit, err)
}
ref := strings.TrimSpace(string(body))
after, ok := strings.CutPrefix(ref, "gitdir:")
if !ok {
return nil, fmt.Errorf("unsupported .git file format in %s", dotGit)
}
p := strings.TrimSpace(after)
if !filepath.IsAbs(p) {
p = filepath.Join(root, p)
}
gitDir = p
}
gitDir, err = filepath.EvalSymlinks(gitDir)
if err != nil {
return nil, fmt.Errorf("canonicalize %s: %w", gitDir, err)
}
commonDir := gitDir
commonDirPath := filepath.Join(gitDir, "commondir")
if data, err := os.ReadFile(commonDirPath); err == nil {
p := strings.TrimSpace(string(data))
if !filepath.IsAbs(p) {
p = filepath.Join(gitDir, p)
}
if cd, err := filepath.EvalSymlinks(p); err == nil {
commonDir = cd
}
}
return &gitPathsResult{gitDir: gitDir, commonDir: commonDir}, nil
}
func readGitOrigin(gp *gitPathsResult) (string, error) {
configPath := filepath.Join(gp.commonDir, "config")
data, err := os.ReadFile(configPath)
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
if err != nil {
return "", fmt.Errorf("read %s: %w", configPath, err)
}
return parseOriginFromGitConfig(string(data)), nil
}
func parseOriginFromGitConfig(body string) string {
inOrigin := false
for _, line := range strings.Split(body, "\n") {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "[") {
inOrigin = trimmed == `[remote "origin"]`
continue
}
if inOrigin {
if after, ok := strings.CutPrefix(trimmed, "url = "); ok {
return after
}
}
}
return ""
}
func readGitCommit(root string) string {
gp, err := gitPaths(root)
if err != nil {
return ""
}
data, err := os.ReadFile(filepath.Join(gp.gitDir, "HEAD"))
if err != nil {
return ""
}
head := strings.TrimSpace(string(data))
if ref, ok := strings.CutPrefix(head, "ref: "); ok {
commitData, err := os.ReadFile(filepath.Join(gp.commonDir, ref))
if err != nil {
return ""
}
return strings.TrimSpace(string(commitData))
}
return head
}
func findRepoRoot(start string) (string, error) {
dir := start
for {
if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil {
return dir, nil
}
parent := filepath.Dir(dir)
if parent == dir {
return "", errors.New("not inside a git repository")
}
dir = parent
}
}
func stateKey(root, githubProject string) string {
input := root + "\n" + githubProject
return fmt.Sprintf("%016x", fnv1a64([]byte(input)))
}
func fnv1a64(b []byte) uint64 {
h := uint64(0xcbf29ce484222325)
for _, c := range b {
h ^= uint64(c)
h *= 0x100000001b3
}
return h
}
func unixNow() uint64 {
return uint64(time.Now().Unix())
}