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
|
package testhelpers
import (
"context"
"crypto/rand"
"encoding/json"
"net/http"
"reflect"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/api"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/gitaly/vendored/gitalypb"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/httpz"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/retry"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/pkg/entity"
"go.opentelemetry.io/otel/trace"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
const (
KASUserAgent = "kas/v0.1-blabla/asdwd"
AgentkToken api.AgentToken = "123123"
AuthSecretKey = "blablabla"
// Copied from gitlab client package because we don't want to export them
jwtRequestHeader = "Gitlab-Kas-Api-Request"
jwtGitLabAudience = "gitlab"
jwtIssuer = "gitlab-kas"
AgentID int64 = 123
ProjectID int64 = 321
UserID int64 = 456
ConfigProjectID int64 = 5
)
// RespondWithJSON marshals response into JSON and writes it into w.
func RespondWithJSON(t *testing.T, w http.ResponseWriter, response interface{}) {
var data []byte
var err error
if m, ok := response.(proto.Message); ok {
data, err = protojson.Marshal(m)
} else {
data, err = json.Marshal(response)
}
if !assert.NoError(t, err) {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header()[httpz.ContentTypeHeader] = []string{"application/json"}
_, err = w.Write(data)
assert.NoError(t, err)
}
func AssertRequestMethod(t *testing.T, r *http.Request, method string) {
assert.Equal(t, method, r.Method)
}
func AssertRequestAccept(t *testing.T, r *http.Request, accept string) {
assert.Equal(t, accept, r.Header.Get(httpz.AcceptHeader))
}
func AssertRequestUserAgent(t *testing.T, r *http.Request, userAgent string) {
assert.Equal(t, userAgent, r.Header.Get(httpz.UserAgentHeader))
}
func AssertRequestAcceptJSON(t *testing.T, r *http.Request) {
AssertRequestAccept(t, r, "application/json")
}
func AssertRequestContentTypeJSON(t *testing.T, r *http.Request) {
assert.Equal(t, "application/json", r.Header.Get(httpz.ContentTypeHeader))
}
func AssertGetJSONRequest(t *testing.T, r *http.Request) {
AssertRequestMethod(t, r, http.MethodGet)
AssertRequestAcceptJSON(t, r)
}
func AssertAgentToken(t *testing.T, r *http.Request, agentToken api.AgentToken) {
assert.EqualValues(t, "Bearer "+agentToken, r.Header.Get(httpz.AuthorizationHeader))
}
func AssertGetJSONRequestIsCorrect(t *testing.T, r *http.Request, traceID trace.TraceID) {
AssertRequestAcceptJSON(t, r)
AssertGetRequestIsCorrect(t, r, traceID)
}
func AssertGetRequestIsCorrect(t *testing.T, r *http.Request, traceID trace.TraceID) {
AssertRequestMethod(t, r, http.MethodGet)
AssertAgentToken(t, r, AgentkToken)
assert.Empty(t, r.Header[httpz.ContentTypeHeader])
AssertCommonRequestParams(t, r, traceID)
AssertJWTSignature(t, r)
}
func AssertCommonRequestParams(t *testing.T, r *http.Request, traceID trace.TraceID) {
AssertRequestUserAgent(t, r, KASUserAgent)
assert.Equal(t, traceID, trace.SpanContextFromContext(r.Context()).TraceID())
}
func AssertJWTSignature(t *testing.T, r *http.Request) {
_, err := jwt.Parse(r.Header.Get(jwtRequestHeader), func(token *jwt.Token) (interface{}, error) {
return []byte(AuthSecretKey), nil
}, jwt.WithAudience(jwtGitLabAudience), jwt.WithIssuer(jwtIssuer), jwt.WithValidMethods([]string{"HS256"}))
assert.NoError(t, err)
}
func CtxWithSpanContext(t *testing.T) (context.Context, trace.TraceID) {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
return InjectSpanContext(t, ctx)
}
func InjectSpanContext(t *testing.T, ctx context.Context) (context.Context, trace.TraceID) {
var traceID trace.TraceID
var spanID trace.SpanID
_, err := rand.Read(traceID[:])
require.NoError(t, err)
_, err = rand.Read(spanID[:])
require.NoError(t, err)
sc := trace.SpanContext{}.WithTraceID(traceID).WithSpanID(spanID)
ctx = trace.ContextWithSpanContext(ctx, sc)
return ctx, traceID
}
func AgentInfoObj() *api.AgentInfo {
return &api.AgentInfo{
ID: AgentID,
ProjectID: ProjectID,
Name: "agent1",
GitalyInfo: &entity.GitalyInfo{
Address: "127.0.0.1:123123",
Token: "abc",
Features: map[string]string{
"bla": "true",
},
},
Repository: &gitalypb.Repository{
StorageName: "StorageName",
RelativePath: "RelativePath",
GitObjectDirectory: "GitObjectDirectory",
GlRepository: "GlRepository",
GlProjectPath: "GlProjectPath",
},
DefaultBranch: "main",
}
}
func RecvMsg(value interface{}) func(any) error {
return func(msg any) error {
SetValue(msg, value)
return nil
}
}
// SetValue sets target to value.
// target must be a pointer. i.e. *blaProtoMsgType
// value must be of the same type as target.
func SetValue(target, value interface{}) {
if targetMsg, ok := target.(proto.Message); ok {
proto.Merge(targetMsg, value.(proto.Message)) // proto messages cannot be just copied
} else {
reflect.ValueOf(target).Elem().Set(reflect.ValueOf(value).Elem())
}
}
func NewPollConfig(interval time.Duration) retry.PollConfigFactory {
return retry.NewPollConfigFactory(interval, retry.NewExponentialBackoffFactory(time.Minute, time.Minute, time.Minute, 2, 1))
}
|