Skip to content

Commit 08f426d

Browse files
committed
Add hook-sdk for golang hooks
Also migrate fpp hook to have a test / example golang hook Signed-off-by: Jannik Hollenbach <jannik.hollenbach@iteratec.com>
1 parent c9c3337 commit 08f426d

30 files changed

Lines changed: 1202 additions & 612 deletions

‎.github/workflows/ci.yaml‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,22 @@ jobs:
163163
working-directory: hooks/${{ matrix.unit }}/hook
164164
run: ./gradlew build --info --warning-mode all
165165

166+
hook-sdk-golang:
167+
name: "Unit-Test | Go Hook SDK"
168+
runs-on: ubuntu-24.04
169+
steps:
170+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
171+
- name: Go Setup
172+
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
173+
with:
174+
go-version-file: "hook-sdk/golang/go.mod"
175+
- name: Test Go Hook SDK
176+
working-directory: ./hook-sdk/golang
177+
run: |
178+
go fmt ./...
179+
go vet ./...
180+
go test ./...
181+
166182
# ---- Build Stage ----
167183

168184
# ---- Build Stage | Operator & Lurker ----
@@ -615,6 +631,11 @@ jobs:
615631
- name: Install bun
616632
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
617633

634+
- name: Go Setup
635+
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
636+
with:
637+
go-version-file: "hooks/finding-post-processing/hook/go.mod"
638+
618639
- name: Install Task
619640
uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0
620641
with:

‎.github/workflows/release-build.yaml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,9 @@ jobs:
260260
- name: Build and Push
261261
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
262262
with:
263-
context: ./hooks/${{ matrix.hook }}/hook
263+
# Go hooks import their SDK from the repository; Node hooks can retain
264+
# their smaller hook-local build contexts.
265+
context: ${{ matrix.hook == 'finding-post-processing' && '.' || format('./hooks/{0}/hook', matrix.hook) }}
264266
file: ./hooks/${{ matrix.hook }}/hook/Dockerfile
265267
build-args: |
266268
namespace=${{ env.DOCKER_NAMESPACE }}

‎documentation/docs/api/finding.md‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ The 'findings.json' file that contains these Findings complies with the followin
2020
"$defs": {
2121
"finding": {
2222
"type": "object",
23-
"additionalProperties": true,
23+
"additionalProperties": false,
2424
"properties": {
2525
"id": {
2626
"description": "The unique identifier for a Finding according to RFC4122.",
@@ -89,14 +89,30 @@ The 'findings.json' file that contains these Findings complies with the followin
8989
"description": "Full URL with protocol, port, and path if existing.",
9090
"type": "string",
9191
"nullable": true
92+
},
93+
"osi_layer": {
94+
"description": "OSI layer associated with the finding.",
95+
"type": "string"
96+
},
97+
"scan": {
98+
"description": "Contains information about the scan that identified the finding.",
99+
"type": "object",
100+
"properties": {
101+
"created_at": {"type": "string", "format": "date-time"},
102+
"name": {"type": "string"},
103+
"namespace": {"type": "string"},
104+
"scan_type": {"type": "string"}
105+
},
106+
"required": ["created_at", "name", "namespace", "scan_type"]
92107
}
93108
},
94109
"required": [
95110
"id",
96111
"parsed_at",
97112
"severity",
98113
"category",
99-
"name"
114+
"name",
115+
"scan"
100116
]
101117
}
102118
}

‎hook-sdk/golang/Taskfile.yaml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# SPDX-FileCopyrightText: the secureCodeBox authors
2+
#
3+
# SPDX-License-Identifier: Apache-2.0
4+
5+
version: "3.48.0"
6+
7+
tasks:
8+
fmt:
9+
cmds:
10+
- go fmt ./...
11+
vet:
12+
cmds:
13+
- go vet ./...
14+
test:
15+
deps: [fmt, vet]
16+
cmds:
17+
- go test ./...

‎hook-sdk/golang/files.go‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// SPDX-FileCopyrightText: the secureCodeBox authors
2+
//
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
package hooksdk
6+
7+
import (
8+
"context"
9+
"encoding/json"
10+
"fmt"
11+
"io"
12+
"log/slog"
13+
"net/http"
14+
"strings"
15+
)
16+
17+
type FileClient interface {
18+
DownloadText(ctx context.Context, url string) (string, error)
19+
DownloadJSON(ctx context.Context, url string, v any) error
20+
Upload(ctx context.Context, url string, contentType string, body []byte) error
21+
}
22+
23+
type httpFileClient struct {
24+
client *http.Client
25+
logger *slog.Logger
26+
}
27+
28+
func NewFileClient(logger *slog.Logger) FileClient {
29+
return &httpFileClient{client: &http.Client{}, logger: logger}
30+
}
31+
32+
func (f *httpFileClient) DownloadText(ctx context.Context, url string) (string, error) {
33+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
34+
if err != nil {
35+
return "", fmt.Errorf("create request: %w", err)
36+
}
37+
resp, err := f.client.Do(req)
38+
if err != nil {
39+
return "", fmt.Errorf("download file: %w", err)
40+
}
41+
defer resp.Body.Close()
42+
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
43+
body, _ := io.ReadAll(resp.Body)
44+
return "", fmt.Errorf("file download failed with status %d: %s", resp.StatusCode, body)
45+
}
46+
body, err := io.ReadAll(resp.Body)
47+
if err != nil {
48+
return "", fmt.Errorf("read response body: %w", err)
49+
}
50+
return string(body), nil
51+
}
52+
53+
func (f *httpFileClient) DownloadJSON(ctx context.Context, url string, v any) error {
54+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
55+
if err != nil {
56+
return fmt.Errorf("create request: %w", err)
57+
}
58+
resp, err := f.client.Do(req)
59+
if err != nil {
60+
return fmt.Errorf("download file: %w", err)
61+
}
62+
defer resp.Body.Close()
63+
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
64+
body, _ := io.ReadAll(resp.Body)
65+
return fmt.Errorf("file download failed with status %d: %s", resp.StatusCode, body)
66+
}
67+
decoder := json.NewDecoder(resp.Body)
68+
decoder.DisallowUnknownFields()
69+
if err := decoder.Decode(v); err != nil {
70+
return fmt.Errorf("decode JSON: %w", err)
71+
}
72+
return nil
73+
}
74+
75+
func (f *httpFileClient) Upload(ctx context.Context, url string, contentType string, body []byte) error {
76+
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, strings.NewReader(string(body)))
77+
if err != nil {
78+
return fmt.Errorf("create request: %w", err)
79+
}
80+
req.Header.Set("Content-Type", contentType)
81+
resp, err := f.client.Do(req)
82+
if err != nil {
83+
return fmt.Errorf("upload file: %w", err)
84+
}
85+
defer resp.Body.Close()
86+
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
87+
responseBody, _ := io.ReadAll(resp.Body)
88+
f.logger.Error("file upload failed", slog.Int("status_code", resp.StatusCode), slog.String("response_body", string(responseBody)))
89+
return fmt.Errorf("file upload failed with status %d: %s", resp.StatusCode, responseBody)
90+
}
91+
return nil
92+
}

‎hook-sdk/golang/findings.go‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// SPDX-FileCopyrightText: the secureCodeBox authors
2+
//
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
package hooksdk
6+
7+
import "strings"
8+
9+
// Reference represents external information about a finding.
10+
type Reference struct {
11+
Type string `json:"type"`
12+
Value string `json:"value"`
13+
}
14+
15+
// FindingScan identifies the scan that produced a finding.
16+
type FindingScan struct {
17+
CreatedAt string `json:"created_at"`
18+
Name string `json:"name"`
19+
Namespace string `json:"namespace"`
20+
ScanType string `json:"scan_type"`
21+
}
22+
23+
// Finding is the strict secureCodeBox finding representation. Scanner-specific
24+
// data belongs in Attributes; other top-level fields are intentionally rejected.
25+
type Finding struct {
26+
ID string `json:"id"`
27+
IdentifiedAt *string `json:"identified_at,omitempty"`
28+
ParsedAt string `json:"parsed_at"`
29+
Name string `json:"name"`
30+
Description *string `json:"description,omitempty"`
31+
Category string `json:"category"`
32+
Severity string `json:"severity"`
33+
Mitigation *string `json:"mitigation,omitempty"`
34+
References []Reference `json:"references,omitempty"`
35+
Attributes map[string]any `json:"attributes,omitempty"`
36+
Location *string `json:"location,omitempty"`
37+
OSILayer string `json:"osi_layer,omitempty"`
38+
Scan FindingScan `json:"scan"`
39+
}
40+
41+
// Scan represents a minimal view of the Scan custom resource.
42+
type Scan struct {
43+
Name string `json:"name"`
44+
Namespace string `json:"namespace"`
45+
UID string `json:"uid"`
46+
Annotations map[string]string `json:"annotations,omitempty"`
47+
Labels map[string]string `json:"labels,omitempty"`
48+
Spec map[string]any `json:"spec,omitempty"`
49+
Status map[string]any `json:"status,omitempty"`
50+
}
51+
52+
func severityCount(findings []Finding, severity string) int {
53+
count := 0
54+
upperSeverity := strings.ToUpper(severity)
55+
for _, finding := range findings {
56+
if strings.ToUpper(finding.Severity) == upperSeverity {
57+
count++
58+
}
59+
}
60+
return count
61+
}
62+
63+
func buildCategoryMap(findings []Finding) map[string]int {
64+
categories := make(map[string]int)
65+
for _, finding := range findings {
66+
categories[finding.Category]++
67+
}
68+
return categories
69+
}

‎hook-sdk/golang/findings_test.go‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// SPDX-FileCopyrightText: the secureCodeBox authors
2+
//
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
package hooksdk
6+
7+
import (
8+
"encoding/json"
9+
"strings"
10+
"testing"
11+
)
12+
13+
func validFinding() Finding {
14+
return Finding{
15+
ID: "b7ac01f4-daf2-42a1-88d4-3389c5a4d918", ParsedAt: "2026-08-25T10:00:00Z", Name: "Open Telnet", Category: "Open Port", Severity: "HIGH",
16+
Attributes: map[string]any{"port": float64(23)},
17+
Scan: FindingScan{CreatedAt: "2026-08-25T09:00:00Z", Name: "scan", Namespace: "default", ScanType: "nmap"},
18+
}
19+
}
20+
21+
func TestValidateFinding(t *testing.T) {
22+
if err := ValidateFinding(validFinding(), 0); err != nil {
23+
t.Fatal(err)
24+
}
25+
finding := validFinding()
26+
finding.Severity = "CRITICAL"
27+
if err := ValidateFinding(finding, 0); err == nil {
28+
t.Fatal("accepted invalid severity")
29+
}
30+
}
31+
32+
func TestDecodeFindingRejectsUnknownTopLevelFields(t *testing.T) {
33+
data, err := json.Marshal(validFinding())
34+
if err != nil {
35+
t.Fatal(err)
36+
}
37+
data = []byte(strings.TrimSuffix(string(data), "}") + `,"ticket":"SCB-1"}`)
38+
decoder := json.NewDecoder(strings.NewReader(string(data)))
39+
decoder.DisallowUnknownFields()
40+
var finding Finding
41+
if err := decoder.Decode(&finding); err == nil {
42+
t.Fatal("accepted unknown top-level field")
43+
}
44+
}
45+
46+
func TestFindingRoundTripKeepsOptionalFieldsOmitted(t *testing.T) {
47+
data, err := json.Marshal(validFinding())
48+
if err != nil {
49+
t.Fatal(err)
50+
}
51+
if strings.Contains(string(data), `"description"`) || strings.Contains(string(data), `"mitigation"`) {
52+
t.Fatalf("emitted omitted optional fields: %s", data)
53+
}
54+
}

‎hook-sdk/golang/go.mod‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// SPDX-FileCopyrightText: the secureCodeBox authors
2+
//
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
module github.com/secureCodeBox/secureCodeBox/hook-sdk/golang
6+
7+
go 1.26.2
8+
9+
require (
10+
k8s.io/apimachinery v0.36.3
11+
k8s.io/client-go v0.36.3
12+
)
13+
14+
require (
15+
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
16+
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
17+
github.com/go-logr/logr v1.4.3 // indirect
18+
github.com/json-iterator/go v1.1.12 // indirect
19+
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
20+
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
21+
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
22+
github.com/x448/float16 v0.8.4 // indirect
23+
go.yaml.in/yaml/v2 v2.4.3 // indirect
24+
golang.org/x/net v0.49.0 // indirect
25+
golang.org/x/oauth2 v0.34.0 // indirect
26+
golang.org/x/sys v0.40.0 // indirect
27+
golang.org/x/term v0.39.0 // indirect
28+
golang.org/x/text v0.33.0 // indirect
29+
golang.org/x/time v0.14.0 // indirect
30+
gopkg.in/inf.v0 v0.9.1 // indirect
31+
k8s.io/klog/v2 v2.140.0 // indirect
32+
k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a // indirect
33+
k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 // indirect
34+
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
35+
sigs.k8s.io/randfill v1.0.0 // indirect
36+
sigs.k8s.io/structured-merge-diff/v6 v6.3.3 // indirect
37+
sigs.k8s.io/yaml v1.6.0 // indirect
38+
)

0 commit comments

Comments
 (0)