Repository navigation
Expand file tree
/
Copy pathgithub.go
More file actions
1141 lines (1077 loc) · 41.6 KB
/
Copy pathgithub.go
File metadata and controls
1141 lines (1077 loc) · 41.6 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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// GitHub delivery: when GITHUB_REPO and GITHUB_TOKEN are set, actionable
// incidents are mirrored to a GitHub issue keyed on the group signature so
// repeated firings update one durable record instead of producing a new chat
// message each time. Unset env means today's chat-only behaviour.
//
// The dedup key is an HTML comment in the body: <!-- alert-triage:{"sig":"..."} -->.
// On re-fire we list open issues, fetch the body of the one carrying the marker,
// and either comment (with flap control) or create the issue. Flap control uses
// the issue's most recent comment timestamp so a re-fire a week later gets a
// comment, but one four minutes later is suppressed.
//
// Issue #14 / Scope: this is the durable record an operator needed. Chat
// delivery stays so a fresh firing still pings the room; the chat line points
// at the issue when one exists.
const signatureMarker = `<!-- alert-triage:{"sig":"%s"} -->`
type gitHubClient struct {
token string
repo string // "owner/name"
hc *http.Client
apiURL string // defaults to https://api.github.com
}
func newGitHub(cfg *Config) *gitHubClient {
if cfg.GitHubToken == "" || cfg.GitHubRepo == "" {
return nil
}
return &gitHubClient{
token: cfg.GitHubToken,
repo: cfg.GitHubRepo,
hc: &http.Client{Timeout: 30 * time.Second},
apiURL: "https://api.github.com",
}
}
type ghIssue struct {
Number int `json:"number"`
Title string `json:"title"`
State string `json:"state"`
HTMLURL string `json:"html_url"`
Body string `json:"body"`
Labels []ghLabel `json:"labels"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Comments int `json:"comments"`
// PullRequest is GitHub's discriminator on the repository /issues
// endpoint: it sets the object on pull-request rows and omits the key on
// genuine issues. listIssues drops rows where it is non-nil. A literal
// "pull_request": null (unobserved on api.github.com) decodes to nil and
// reads as a genuine issue; degrading that way toward a visible marker
// match beats silently dropping a real issue and duplicating the
// incident.
PullRequest *ghPullRef `json:"pull_request"`
}
// ghPullRef reads just enough of a pull-request row's pull_request object;
// the pointer's presence is the whole judgement, so the fields exist only to
// give it a decodable shape.
type ghPullRef struct {
URL string `json:"url"`
}
type ghLabel struct {
Name string `json:"name"`
}
// issueAction tells main.go what happened: "created", "commented" or "none"
// (no env, not actionable, or no change worth posting). The URL is set when an
// issue now exists so chat can link to it.
type issueAction struct {
Outcome string // created | commented | none
URL string
}
// deliverGitHub routes the incident to GitHub. It is a no-op when the env is
// unset or the triage verdict is non-actionable; chat-only groups never touch
// the API. Returns (action, err): action.Outcome=="none" with err==nil is the
// expected path for the majority of groups.
func deliverGitHub(ctx context.Context, gh *gitHubClient, cfg *Config, r Report) (issueAction, error) {
if gh == nil {
return issueAction{Outcome: "none"}, nil
}
if !r.Triage.Actionable() {
return issueAction{Outcome: "none"}, nil
}
sig := r.Group.Signature()
if sig == "" {
return issueAction{Outcome: "none"}, nil
}
existing, err := gh.findOpenIssue(ctx, sig)
if err != nil {
return issueAction{}, err
}
body := renderIssueBody(r, sig)
if existing == nil {
title := issueTitle(r)
num, url, err := gh.createIssue(ctx, title, body, labelsFor(r))
if err != nil {
return issueAction{}, err
}
logf("github: created issue #%d for %s", num, sig)
return issueAction{Outcome: "created", URL: url}, nil
}
// Already open. Comment only when the state changed or enough time has
// passed since the last comment; otherwise we are exactly the flapping
// alert the issue warned about.
if shouldComment(existing, r, cfg.IssueCommentInterval) {
body := renderCommentBody(r)
if err := gh.comment(ctx, existing.Number, body); err != nil {
return issueAction{}, err
}
logf("github: commented on #%d for %s", existing.Number, sig)
// Synchronize the stored severity so a repeated fire at THIS severity
// obeys the interval gate instead of re-tripping the severity-change
// gate forever (issue #171). Best-effort: the comment is already
// delivered, so a failed label update degrades to the old behaviour
// (this severity may re-comment once) and is only logged.
if want := severityLabel(r.Group.Severity()); want != "" && !hasLabel(existing.Labels, want) {
if err := gh.setSeverityLabel(ctx, existing.Number, existing.Labels, want); err != nil {
logf("github: commented on #%d but could not sync severity label %q: %v", existing.Number, want, err)
}
}
return issueAction{Outcome: "commented", URL: existing.HTMLURL}, nil
}
return issueAction{Outcome: "none", URL: existing.HTMLURL}, nil
}
// shouldComment gates re-fire comments. Two reasons to post: the severity
// moved (so the issue reflects the current state) or the last comment is older
// than the flap interval. PriorSeen contributes a "fired N times recently"
// line which is what makes the comment worthwhile. The severity gate is not
// permanently true: deliverGitHub re-stamps the issue's severity label after
// a successful comment, so a repeat at the same severity falls through to
// the interval gate (issue #171).
func shouldComment(existing *ghIssue, r Report, interval time.Duration) bool {
if interval <= 0 {
interval = 12 * time.Hour
}
// Severity change always warrants a note. Only judge a change when the
// issue actually carries labels: labelsFor stamps one severity label on
// creation, so a missing current-severity label means the severity moved.
// hasLabel is the same scan deliverGitHub runs before the label sync, so
// both sites judge the label set identically.
if want := severityLabel(r.Group.Severity()); want != "" && len(existing.Labels) > 0 && !hasLabel(existing.Labels, want) {
return true
}
// If we've never commented on this issue yet, the first re-fire is
// always worth a note — the initial body captured the first firing, but
// operators want to see "still happening" written down somewhere.
if existing.Comments == 0 {
return true
}
return time.Since(existing.UpdatedAt) >= interval
}
func issueTitle(r Report) string {
// "KubePodNotReady (warning)" — short, sorts in the issue list, and the
// signature marker inside the body still does the dedup work.
sev := r.Group.Severity()
if sev == "" {
sev = "alert"
}
return fmt.Sprintf("%s (%s)", r.Group.Title(), sev)
}
func labelsFor(r Report) []string {
out := []string{"alert-triage"}
if s := severityLabel(r.Group.Severity()); s != "" {
out = append(out, s)
}
return out
}
// severityLabel normalises a severity for use as a label value. Every value
// passes through unchanged apart from case and surrounding space: whether a
// name is one of the severity labels this service manages is
// isSeverityLabel's judgement, not this one's.
func severityLabel(s string) string {
return strings.ToLower(strings.TrimSpace(s))
}
// isSeverityLabel reports whether name is one of the severity labels this
// service manages (the set labelsFor can stamp). Non-severity labels — the
// alert-triage marker and anything an operator adds — are never severity
// labels and must survive a severity sync.
func isSeverityLabel(name string) bool {
switch strings.ToLower(strings.TrimSpace(name)) {
case "critical", "warning", "info":
return true
}
return false
}
// hasLabel reports whether the label set already carries name.
func hasLabel(labels []ghLabel, name string) bool {
for _, l := range labels {
if l.Name == name {
return true
}
}
return false
}
// renderIssueBody is the full GitHub-flavoured Markdown body. Chat delivery
// loses evidence when it's verbose; a folded <details> block solves that.
// The signature marker is required for dedup and must be the first line so a
// quick text search picks it up before any quoting.
func renderIssueBody(r Report, sig string) string {
var b strings.Builder
fmt.Fprintf(&b, signatureMarker+"\n\n", sig)
if r.Narrative != "" {
b.WriteString(r.Narrative)
b.WriteString("\n\n")
}
if loc := r.Triage.FixLocation; loc != "" && loc != "unknown" {
fmt.Fprintf(&b, "**Fix belongs in:** `%s`", loc)
if r.Triage.Confidence == "low" {
b.WriteString(" _(low confidence)_")
}
b.WriteString("\n\n")
}
if w := r.Triage.WhatToChange; w != "" {
fmt.Fprintf(&b, "**What to change**\n\n%s\n\n", w)
}
// Grafana Explore links: same construction as the Discord embed, so the
// issue body and the chat digest agree on where the evidence lives. Links
// are emitted only when GRAFANA_URL and the relevant datasource UID are
// set; otherwise the body reads exactly as it did before.
if metricsLink, logsLink := grafanaLinks(r.Cfg, firstExpression(r.Group.Alerts), firstNamespace(r.Group.Alerts), groupWindow(r.Group)); metricsLink != "" || logsLink != "" {
b.WriteString("**Grafana**\n\n")
if metricsLink != "" {
fmt.Fprintf(&b, "• [Metrics explore](%s)\n", metricsLink)
}
if logsLink != "" {
fmt.Fprintf(&b, "• [Logs explore](%s)\n", logsLink)
}
b.WriteString("\n")
}
b.WriteString("**Alerts**\n\n")
b.WriteString("| Severity | Alert | Namespace | Since |\n")
b.WriteString("| --- | --- | --- | --- |\n")
for _, a := range r.Group.Alerts {
// The three cells read fixed label values, which bypass the payload's
// sanitized copies; the same keyword engine keeps a credential-shaped
// value in one of them out of the durable body (#269 review).
ns := stripSecrets(a.namespace())
if ns == "" {
ns = "—"
}
since := "—"
if !a.StartsAt.IsZero() {
since = a.StartsAt.UTC().Format(time.RFC3339)
}
fmt.Fprintf(&b, "| %s | `%s` | %s | %s |\n", stripSecrets(a.severity()), stripSecrets(a.name()), ns, since)
}
b.WriteString("\n")
// renderEvidence always renders at least the identity block, so the
// evidence section is unconditional; the old empty-skip guard guarded
// nothing.
fmt.Fprintf(&b, "<details><summary>Evidence</summary>\n\n%s\n\n</details>\n\n", renderEvidence(r))
payloadJSON := renderPayload(r)
if payloadJSON != "" {
fmt.Fprintf(&b, "<details><summary>Raw Alertmanager payload</summary>\n\n```json\n%s\n```\n\n</details>\n",
clamp(payloadJSON, 60000))
}
return b.String()
}
// renderCommentBody is the briefer form used on re-fire. It records the new
// firing count and any severity shift; full body rebuild is unnecessary and
// noisy.
func renderCommentBody(r Report) string {
var b strings.Builder
b.WriteString("**Re-fire**\n\n")
if r.PriorSeen > 0 {
fmt.Fprintf(&b, "Seen %d time(s) recently.\n\n", r.PriorSeen)
}
if r.Narrative != "" {
b.WriteString(clamp(r.Narrative, 1500))
b.WriteString("\n\n")
}
fmt.Fprintf(&b, "Severity: `%s`\n", r.Group.Severity())
return b.String()
}
func renderPayload(r Report) string {
type payloadView struct {
Group string `json:"group"`
Status string `json:"status"`
Alerts []Alert `json:"alerts"`
}
pv := payloadView{
Group: r.Group.Key,
Status: "firing",
Alerts: sanitizedAlerts(r.Group.Alerts),
}
b, err := json.MarshalIndent(pv, "", " ")
if err != nil {
return ""
}
return string(b)
}
// sanitizedAlerts copies alerts with credential-bearing label and annotation
// values redacted (issue #269). The issue is a durable record, so unlike the
// chat digest it keeps everything the payload carries; without this pass a
// description containing password=..., a Bearer header, or a JSON-quoted
// token is copied into the issue verbatim even though pod and backend logs
// are redacted.
//
// The originals must survive untouched: correlation, history, the model
// prompt and the Discord digest all read the same maps, and redacting them
// in place would delete evidence from paths where the leak was never the
// risk. So every map is rebuilt rather than modified.
func sanitizedAlerts(alerts []Alert) []Alert {
if alerts == nil {
// Preserve the serialized shape: a nil slice marshals as null, and an
// empty-but-non-nil one as []. Rebuilding only what exists keeps the
// payload byte-identical apart from redaction.
return nil
}
out := make([]Alert, len(alerts))
copy(out, alerts)
for i := range out {
// Fingerprint and Status are as sender-controlled as any label, and
// this payload block is a durable verbatim echo. A real Alertmanager
// fingerprint is a hex hash, but the webhook token fails open, so a
// poster can put anything in either field; both pass the same gate as
// the maps (#278 review).
out[i].Fingerprint = stripSecrets(out[i].Fingerprint)
out[i].Status = stripSecrets(out[i].Status)
if out[i].Labels != nil {
out[i].Labels = sanitizedMetadata(out[i].Labels)
}
if out[i].Annotations != nil {
out[i].Annotations = sanitizedMetadata(out[i].Annotations)
}
}
return out
}
// sanitizedMetadata copies m with every value passed through safeMetadataValue,
// the same redaction the evidence renderers apply. Sanitizing per value rather
// than the marshalled JSON keeps the payload valid: the keyword patterns end
// in \S+, which on serialized JSON would swallow the closing quote of a
// string and corrupt the document.
func sanitizedMetadata(m map[string]string) map[string]string {
out := make(map[string]string, len(m))
for k, v := range m {
out[k] = safeMetadataValue(k, v)
}
return out
}
// findOpenIssue lists open issues labelled alert-triage and returns the one
// whose body contains the signature marker. Pagination stops at the first
// match; the API caps results at 100 per page which is fine for the
// steady-state of an alert-triage queue.
func (g *gitHubClient) findOpenIssue(ctx context.Context, sig string) (*ghIssue, error) {
marker := fmt.Sprintf(signatureMarker, sig)
page := 1
for {
issues, next, err := g.listIssues(ctx, page, 100, "open")
if err != nil {
return nil, err
}
for i := range issues {
if strings.Contains(issues[i].Body, marker) {
return &issues[i], nil
}
}
if next == 0 {
return nil, nil
}
page = next
if page > 20 { // safety: 2000 open issues is enough
return nil, nil
}
}
}
// ghListBodyCap bounds how much of a paginated GitHub list response (issues,
// PRs) we'll buffer before failing the read. It aliases metricsBodyCap
// (4 MiB): the list endpoints are not known-small — findOpenIssue pages at
// 100 issues whose bodies each carry a full digest — so they take the shared
// bulk ceiling rather than a tighter guess.
const ghListBodyCap = metricsBodyCap
// ghSmallBodyCap bounds single-object GitHub replies (an issue create
// response, the repo record, a ref): the payload is known to be small, so the
// ceiling sits far below the bulk caps and anything larger is a misbehaving
// endpoint, not a real reply.
const ghSmallBodyCap = 64 << 10
// listIssues returns one page of issues. The custom media type asks for the
// issues' labels inline so we don't have to fan out a second request per row
// just to compute the severity-change check.
func (g *gitHubClient) listIssues(ctx context.Context, page, perPage int, state string) ([]ghIssue, int, error) {
u, _ := url.Parse(g.apiURL + "/repos/" + g.repo + "/issues")
q := u.Query()
q.Set("state", state)
q.Set("labels", "alert-triage")
q.Set("per_page", fmt.Sprintf("%d", perPage))
q.Set("page", fmt.Sprintf("%d", page))
u.RawQuery = q.Encode()
resp, err := g.doRequest(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, 0, fmt.Errorf("github: repo %q not found or token lacks access", g.repo)
}
if resp.StatusCode >= 300 {
return nil, 0, githubStatusError("github list", resp)
}
var raw []ghIssue
body, err := readCappedBody(resp.Body, ghListBodyCap)
if err != nil {
return nil, 0, fmt.Errorf("github list: %w", err)
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, 0, err
}
// The /issues endpoint also returns pull requests; drop them on the
// pull_request discriminator, never on body content. The marker search
// cannot reject PRs: pull.go aliases prMarker to signatureMarker so a
// generated PR body carries the same marker an incident issue would, and
// a PR that gains the alert-triage label would otherwise be mistaken for
// the open incident, suppressing the real issue and sending re-fire
// comments to the PR (issue #272).
issues := make([]ghIssue, 0, len(raw))
for _, i := range raw {
if i.PullRequest != nil {
continue
}
issues = append(issues, i)
}
next := 0
if link := resp.Header.Get("Link"); link != "" {
next = parseNextPage(link)
}
return issues, next, nil
}
// parseNextPage extracts the next page number from a GitHub Link header by
// reading the URL parseLinkNext returns, so the issue and PR pagination
// scans and the commit-file scan read the same header the same way.
func parseNextPage(link string) int {
href := parseLinkNext(link)
if href == "" {
return 0
}
u, err := url.Parse(href)
if err != nil {
return 0
}
page := u.Query().Get("page")
if page == "" {
return 0
}
var n int
fmt.Sscanf(page, "%d", &n)
return n
}
func (g *gitHubClient) createIssue(ctx context.Context, title, body string, labels []string) (int, string, error) {
payload := map[string]any{
"title": title,
"body": body,
"labels": labels,
}
resp, err := g.doRequest(ctx, http.MethodPost, g.apiURL+"/repos/"+g.repo+"/issues", payload)
if err != nil {
return 0, "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return 0, "", githubStatusError("github create", resp)
}
var out ghIssue
respBody, err := readCappedBody(resp.Body, ghSmallBodyCap)
if err != nil {
return 0, "", fmt.Errorf("github create: %w", err)
}
if err := json.Unmarshal(respBody, &out); err != nil {
return 0, "", err
}
return out.Number, out.HTMLURL, nil
}
func (g *gitHubClient) comment(ctx context.Context, number int, body string) error {
payload := map[string]string{"body": body}
u := fmt.Sprintf("%s/repos/%s/issues/%d/comments", g.apiURL, g.repo, number)
resp, err := g.doRequest(ctx, http.MethodPost, u, payload)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return githubStatusError("github comment", resp)
}
return nil
}
// setSeverityLabel replaces the issue's severity label with want, leaving all
// non-severity labels (alert-triage, operator-added labels) untouched. The
// labels endpoint replaces the whole set, so we resend the non-severity labels
// we want to keep and drop any stale severity label this service manages, then
// append the new severity. want is itself a severity label, so it cannot
// duplicate a kept label.
func (g *gitHubClient) setSeverityLabel(ctx context.Context, number int, existing []ghLabel, want string) error {
labels := make([]string, 0, len(existing)+1)
for _, l := range existing {
if isSeverityLabel(l.Name) {
continue
}
labels = append(labels, l.Name)
}
labels = append(labels, want)
payload := map[string]any{"labels": labels}
u := fmt.Sprintf("%s/repos/%s/issues/%d/labels", g.apiURL, g.repo, number)
resp, err := g.doRequest(ctx, http.MethodPut, u, payload)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return githubStatusError("github labels", resp)
}
return nil
}
func (g *gitHubClient) setHeaders(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+g.token)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
req.Header.Set("User-Agent", "alert-triage")
}
// doRequest builds and sends one GitHub API request. A non-nil payload is
// JSON-encoded and sent with the matching Content-Type; a nil payload sends no
// body, which is every read path. Status handling stays at the call sites: a
// 404, 403 or 422 means something specific enough that folding it into one
// generic error here would lose it. The response body is left open for the
// caller to read and close.
func (g *gitHubClient) doRequest(ctx context.Context, method, rawURL string, payload any) (*http.Response, error) {
var body io.Reader
if payload != nil {
buf, err := json.Marshal(payload)
if err != nil {
return nil, err
}
body = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
if err != nil {
return nil, err
}
g.setHeaders(req)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
return g.hc.Do(req)
}
// githubStatusError formats a non-success GitHub response: the caller's label, the
// HTTP status, and a bounded sample of the body. The sample is capped so a
// verbose proxy error cannot fill memory; a caller that needs a specific
// message for a status checks it before reaching here.
func githubStatusError(prefix string, resp *http.Response) error {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("%s: %s: %s", prefix, resp.Status, string(body))
}
// Commit relevance for a Flux reconcile. A healthy Flux reconcile is neutral
// (see fluxActivity), but when the source is GitHub we can fetch the commit
// that the revision references and check whether its changed files intersect
// the workload's GitOps path or declared component paths. The evidence is
// deliberately best-effort: a non-GitHub source, a private-repo 404, an
// unparseable revision, or any API failure degrades to Unknown so the digest
// keeps shipping instead of being blocked on an external lookup.
//
// The State values are the three the issue asks for:
// - "touches" - the commit changed at least one file under the
// workload path or one of the declared component
// paths.
// - "does_not_touch" - the commit was fetched successfully and no changed
// file intersects the workload/component paths.
// - "unknown" - any other reason: unsupported host, unparseable
// revision, API failure, private-repo auth failure,
// or empty workload path.
const (
commitRelevanceTouches = "touches"
commitRelevanceDoesNotTouch = "does_not_touch"
commitRelevanceUnknown = "unknown"
)
// CommitRelevance is the result of classifying a reconciled GitHub commit
// against the workload's Git surface. Fields are populated as far as the
// lookup could get; Reason is always human-readable and is the single thing
// the rendering layer shows when State is "unknown" so the operator can see
// why the check degraded. CommitMessage is the raw commit message body and
// is treated as untrusted external text by the renderer; the page also
// never carries the full message — only a short, flattened summary line.
type CommitRelevance struct {
State string // touches | does_not_touch | unknown
RepoURL string // e.g. https://github.com/owner/repo
Revision string // the full Flux revision string the lookup tried
SHA string // the bare SHA the API was queried with
WorkloadPath string // repository-relative workload path that was checked
ComponentPaths []string // repository-relative component paths (issue #134)
MatchingPaths []string // subset of changed files that matched
CommitMessage string // short, flattened message; treated as untrusted
Reason string // short explanation; shown only when State == "unknown"
}
// parseGitHubRepoURL extracts the owner/name from a GitHub repository URL.
// Accepted forms:
// - https://github.com/<owner>/<repo>[.git]
// - http://github.com/<owner>/<repo>[.git]
// - git@github.com:<owner>/<repo>[.git]
// - ssh://git@github.com/<owner>/<repo>[.git]
//
// Non-github.com hosts (a self-hosted Enterprise host, a GitLab URL) return
// ("", "", false) so the lookup degrades to "unknown" rather than guessing.
// Trailing ".git", trailing slashes, and the auth segment are stripped before
// the owner/repo pair is extracted. This is a string parser, not a URL parser:
// the GitHub Enterprise case has too many forms to be worth a full parse.
func parseGitHubRepoURL(raw string) (owner, name string, ok bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", "", false
}
// Normalise the scp-style ssh form ("git@github.com:owner/repo")
// to "ssh://git@github.com/owner/repo" so the url.Parse below can
// extract the host: the standard library treats the scp form as a
// single opaque path.
if i := strings.Index(raw, "@"); i >= 0 && !strings.Contains(raw[i:], "://") {
// Find the first ':' after the '@', which separates the
// host from the path in scp syntax.
rest := raw[i+1:]
if j := strings.Index(rest, ":"); j >= 0 {
host := rest[:j]
path := rest[j+1:]
raw = "ssh://" + raw[:i] + "@" + host + "/" + path
}
}
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
// Maybe the input was just "github.com/owner/repo"; split on '/'.
parts := strings.Split(strings.TrimLeft(raw, "/"), "/")
return matchGitHubHost(parts)
}
host := strings.ToLower(u.Host)
if i := strings.Index(host, ":"); i >= 0 {
host = host[:i]
}
if host != "github.com" {
return "", "", false
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
// parts is [owner, repo]; reject anything longer so a stray
// fragment does not produce a malformed lookup.
return splitOwnerRepo(parts)
}
// matchGitHubHost turns ["github.com", owner, repo(.git?)] into (owner, repo)
// for the case where the input lacked a scheme and the host ended up in
// the path. Anything other than exactly three path elements is rejected.
func matchGitHubHost(parts []string) (owner, name string, ok bool) {
if len(parts) == 3 && strings.EqualFold(parts[0], "github.com") {
return splitOwnerRepo(parts[1:])
}
return "", "", false
}
// splitOwnerRepo turns [owner, repo] into (owner, repo-without-.git).
// Rejects empty entries so a stray fragment or double slash cannot
// produce a malformed repo lookup.
func splitOwnerRepo(parts []string) (owner, name string, ok bool) {
if len(parts) != 2 {
return "", "", false
}
o, r := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
if o == "" || r == "" {
return "", "", false
}
return o, strings.TrimSuffix(r, ".git"), true
}
// parseFluxRevisionSHA extracts a usable SHA from a Flux revision string.
// Flux v2 stamps revisions in the form:
//
// refs/heads/<branch>@sha1:<40-char-hex>
// refs/tags/<tag>@sha1:<40-char-hex>
// <branch>@sha1:<40-char-hex>
// sha1:<40-char-hex>
// <40-char-hex>
//
// Any revision string that does not carry a 40-character lowercase or
// uppercase hex SHA returns ("", false) so the GitHub lookup degrades to
// "unknown" rather than firing an API request that the server will reject.
// The algorithm prefix is hard-coded to "sha1" because that is what Flux
// stamps today; a future "sha256:" prefix would be a separate change so
// it is rejected rather than silently coerced.
func parseFluxRevisionSHA(rev string) (sha string, ok bool) {
rev = strings.TrimSpace(rev)
if rev == "" {
return "", false
}
// Accept either "<algo>:<hex>" (when the part before ":" looks like
// a Flux ref) or a bare 40-char hex. The two arms are kept separate
// so a future algorithm prefix is a single-line change rather than
// a rewrite of this branch.
if i := strings.Index(rev, ":"); i >= 0 {
head := rev[:i]
algo := head
if j := strings.LastIndex(head, "@"); j >= 0 {
algo = head[j+1:]
}
if algo != "sha1" {
return "", false
}
rev = rev[i+1:]
}
if !isHex40(rev) {
return "", false
}
return strings.ToLower(rev), true
}
// isHex40 is true for a 40-character string of [0-9a-fA-F]. SHA-1 is the
// algorithm Flux stamps today; a 64-character SHA-256 revision is not
// currently produced by Flux but the helper is kept strict so the parser
// does not silently accept a truncated value.
func isHex40(s string) bool {
// The hex scan is enrich_redact.go's isHexRun; the length bound is what
// keeps this strict to SHA-1.
return len(s) == 40 && isHexRun(s)
}
// pathIntersects reports whether any changed file lives under one of the
// declared workload paths. The matching paths are returned so the renderer
// can list exactly which files were the trigger; the workload path and any
// declared component paths are all considered equivalent (a component is
// part of the workload's effective Git surface per #134).
//
// All comparisons are done on cleaned, repository-relative paths: leading
// and trailing slashes are stripped, ".." segments are collapsed, and the
// match is a path-prefix check so a workload at "apps/payments" matches a
// changed file at "apps/payments/deployment.yaml". The comparison is also
// anchored at the path boundary, so a workload at "app" does NOT match a
// changed file at "application/x" — the prefix has to land on a segment
// boundary, otherwise unrelated directories fuse.
func pathIntersects(workloadPath string, componentPaths, changedFiles []string) []string {
var matches []string
roots := make([]string, 0, 1+len(componentPaths))
if w := cleanRepoPath(workloadPath); w != "" {
roots = append(roots, w)
}
for _, c := range componentPaths {
if cp := cleanRepoPath(c); cp != "" && cp != cleanRepoPath(workloadPath) {
roots = append(roots, cp)
}
}
if len(roots) == 0 {
return nil
}
for _, f := range changedFiles {
cf := cleanRepoPath(f)
if cf == "" {
continue
}
for _, root := range roots {
if cf == root || strings.HasPrefix(cf, root+"/") {
matches = append(matches, f)
break
}
}
}
return matches
}
// resolveWorkloadPaths normalizes the workload path and each declared
// component path to repository-relative form. Flux documents
// spec.components as local, relative paths: every component is relative to
// the Kustomization's spec.path (the workload path), not to the repo root.
// So each component is resolved against the workload path using repo path
// semantics, whether or not it contains "..": a component "deploy/prod"
// under workload "apps/payments" is "apps/payments/deploy/prod", and
// "../shared" under workload "apps/payments/prod" is "apps/payments/shared".
// A component that resolves above the repo root (a malformed spec) is
// reported as not-ok; it would match changed files that are not part of
// this workload's Git surface, so the caller degrades to "unknown".
func resolveWorkloadPaths(workloadPath string, componentPaths []string) ([]string, bool) {
base := cleanRepoPath(workloadPath)
if base == "" {
return nil, false
}
resolved := make([]string, 0, len(componentPaths))
for _, c := range componentPaths {
rel := joinRepoPaths(base, c)
if rel == "" {
// Escapes the repo root: reject the whole lookup.
return nil, false
}
resolved = append(resolved, rel)
}
return resolved, true
}
// joinRepoPaths resolves a component path against a base repo-relative
// path, returning "" when the result escapes the repo root. Uses
// repository (Unix) path semantics. The component is split on its raw
// form: ".." segments are the very thing being resolved, so they must
// survive (cleanRepoPath would have dropped them). A component without
// any ".." simply appends its segments to the base, which is exactly
// how Flux's local relative component paths compose.
func joinRepoPaths(base, comp string) string {
parts := strings.Split(cleanRepoPath(base), "/")
for _, seg := range strings.Split(strings.TrimLeft(comp, "/"), "/") {
switch seg {
case "", ".":
continue
case "..":
if len(parts) == 0 {
// Escapes the repo root.
return ""
}
parts = parts[:len(parts)-1]
default:
parts = append(parts, seg)
}
}
return strings.Join(parts, "/")
}
// cleanRepoPath trims leading/trailing slashes and collapses redundant
// separators without using filepath.Clean (which is OS-dependent — this is
// always a Unix-style Git path). A leading ".." or "." collapses to "" so
// the caller can drop it; the digest never renders traversal attempts.
func cleanRepoPath(p string) string {
p = strings.TrimSpace(p)
p = strings.TrimLeft(p, "/")
p = strings.TrimRight(p, "/")
if p == "" {
return ""
}
// Replace any run of '/' with a single one, then split on '/' so
// ".." segments can be removed the same way path.Clean would for a
// repository-relative path.
parts := strings.Split(strings.ReplaceAll(p, "\\", "/"), "/")
out := parts[:0]
for _, seg := range parts {
switch seg {
case "", ".":
continue
case "..":
// Reaching a parent of the repo root is meaningless here;
// drop the segment so we never emit a path that escapes.
continue
default:
out = append(out, seg)
}
}
return strings.Join(out, "/")
}
// fetchCommitFiles retrieves the full list of files changed in a single
// commit, following the endpoint's pagination. ownerRepo is the
// "owner/name" the commit belongs to — derived from the workload's
// GitRepository URL, not necessarily the configured GITHUB_REPO the client
// was built against (the token and HTTP client are reused across repos; only
// the /repos/ path changes).
//
// The commit endpoint is paginated: a large commit (a mass rename) can
// spread its files across multiple pages of up to 300. We follow the Link
// rel="next" header until there is no next page so an incomplete file list
// never turns into a confident "does not touch" — the whole point of the
// lookup (issue #135) is a positive negative, and that only holds when the
// file set is complete. A hard page cap bounds a misbehaving proxy that
// repeats rel="next"; hitting it is an error so the caller degrades to
// "unknown".
//
// A 404 (the most common non-success — private-repo auth failure, a fork
// the token cannot see, a never-existed SHA) is folded into the err return
// so the caller can label the relevance "unknown". Network errors,
// timeouts, and 5xx all bubble up untouched so the caller can decide
// whether to log them. The 1 MiB per-page decode cap (in fetchCommitPage)
// keeps a misbehaving proxy returning a verbose error body from blowing
// memory.
func (g *gitHubClient) fetchCommitFiles(ctx context.Context, ownerRepo, sha string) ([]string, error) {
if g == nil {
return nil, fmt.Errorf("github: no client")
}
if ownerRepo == "" {
return nil, fmt.Errorf("github: empty repo")
}
if sha == "" {
return nil, fmt.Errorf("github: empty sha")
}
// 300 is the documented per-page maximum for this endpoint; per_page is
// fixed on the first page and carried forward in each rel="next" URL.
url := g.apiURL + "/repos/" + ownerRepo + "/commits/" + sha + "?per_page=300"
// 300 files/page * 100 pages = 30k files, far beyond any real commit.
const maxPages = 100
var out []string
for i := 0; ; i++ {
if i >= maxPages {
return nil, fmt.Errorf("github: commit %s file list incomplete (reached %d pages)", sha, maxPages)
}
files, next, err := g.fetchCommitPage(ctx, url)
if err != nil {
return nil, err
}
out = append(out, files...)
if next == "" {
break
}
url = next
}
return out, nil
}
// fetchCommitPage fetches one page of the commit endpoint and returns the
// file names on that page plus the URL of the next page (from the Link
// rel="next" header) or "" when there is no next page.
//
// A renamed file contributes BOTH its new (filename) and old
// (previous_filename) path: a move out of the workload still changes the
// workload's Git surface, so dropping the old path would turn that into a
// false "does not touch" (issue #185).
func (g *gitHubClient) fetchCommitPage(ctx context.Context, url string) ([]string, string, error) {
resp, err := g.doRequest(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, "", fmt.Errorf("github: commit not found or token lacks access")
}
if resp.StatusCode == http.StatusForbidden {
// Rate-limited or private-repo permission denied; the message
// is not actionable for the operator, so collapse to one shape.
return nil, "", fmt.Errorf("github: commit forbidden (rate limit or permissions)")
}
if resp.StatusCode >= 300 {
return nil, "", githubStatusError("github commit", resp)
}
var payload struct {
Files []struct {
Filename string `json:"filename"`
Status string `json:"status"`
PreviousFilename string `json:"previous_filename"`
} `json:"files"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&payload); err != nil {
return nil, "", fmt.Errorf("github commit decode: %w", err)
}
out := make([]string, 0, len(payload.Files))
for _, f := range payload.Files {
if f.Filename != "" {
out = append(out, f.Filename)
}
// A rename's source path stays in the changed set (issue #185).
if f.Status == "renamed" && f.PreviousFilename != "" {
out = append(out, f.PreviousFilename)
}
}