Skip to content

Commit

Permalink
fix: unit test and lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ffforest committed Aug 16, 2024
1 parent 5946ca7 commit 7b36317
Show file tree
Hide file tree
Showing 13 changed files with 36 additions and 40 deletions.
4 changes: 1 addition & 3 deletions pkg/cmd/server/source.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ import (
"github.com/spf13/pflag"
)

var (
ErrDefaultSourceRemoteNotSpecified = errors.New("--default-source-remote must be specified")
)
var ErrDefaultSourceRemoteNotSpecified = errors.New("--default-source-remote must be specified")

// DefaultSourceOptions holds the default backend access layer configurations.
type DefaultSourceOptions struct {
Expand Down
4 changes: 1 addition & 3 deletions pkg/domain/constant/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,4 @@ const (
TmpDirPrefix = "/tmp"
)

var (
ErrResourceHasNilStack = errors.New("resource has nil stack")
)
var ErrResourceHasNilStack = errors.New("resource has nil stack")
2 changes: 1 addition & 1 deletion pkg/domain/entity/workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ type Workspace struct {

type SecretValue struct {
SecretStore *SecretStore `json:"secretStore"`
//Value to store in the secret store.
// Value to store in the secret store.
Value string `json:"value"`
// Ref will only return with the update secret variable
Ref string `json:"ref"`
Expand Down
2 changes: 1 addition & 1 deletion pkg/engine/runtime/terraform/tfops/workspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ func TestWorkSpace_ShowPlan(t *testing.T) {
}
r := jsonutil.Marshal2PrettyString(got)
if !reflect.DeepEqual(r, string(data)) {
t.Errorf("ShowPlan() got = %v, want %v", got, data)
t.Errorf("ShowPlan() got = %v, want %v", r, string(data))
}
})
}
Expand Down
10 changes: 0 additions & 10 deletions pkg/infra/persistence/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,6 @@ func (r *backendRepository) Get(ctx context.Context, id uint) (*entity.Backend,
return dataModel.ToEntity()
}

// GetByName retrieves a backend by its name.
func (r *backendRepository) GetByName(ctx context.Context, name string) (*entity.Backend, error) {
var dataModel BackendModel
err := r.db.WithContext(ctx).Where("name = ?", name).First(&dataModel).Error
if err != nil {
return nil, err
}
return dataModel.ToEntity()
}

// List retrieves all backends.
func (r *backendRepository) List(ctx context.Context) ([]*entity.Backend, error) {
var dataModel []BackendModel
Expand Down
4 changes: 2 additions & 2 deletions pkg/server/handler/stack/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ func requestHelper(r *http.Request) (context.Context, *httplog.Logger, *stackman
dryrunParam, _ := strconv.ParseBool(r.URL.Query().Get("dryrun"))
forceParam, _ := strconv.ParseBool(r.URL.Query().Get("force"))
importResourcesParam, _ := strconv.ParseBool(r.URL.Query().Get("importResources"))
specIdParam := r.URL.Query().Get("specID")
specIDParam := r.URL.Query().Get("specID")
// TODO: Should match automatically eventually???
workspaceParam := r.URL.Query().Get("workspace")
operatorParam, err := authutil.GetSubjectFromUnverifiedJWTToken(ctx, r)
Expand All @@ -254,7 +254,7 @@ func requestHelper(r *http.Request) (context.Context, *httplog.Logger, *stackman
Detail: detailParam,
Dryrun: dryrunParam,
Force: forceParam,
SpecID: specIdParam,
SpecID: specIDParam,
ImportResources: importResourcesParam,
}
params := stackmanager.StackRequestParams{
Expand Down
3 changes: 2 additions & 1 deletion pkg/server/manager/project/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ type ProjectManager struct {
func NewProjectManager(projectRepo repository.ProjectRepository,
organizationRepo repository.OrganizationRepository,
sourceRepo repository.SourceRepository,
defaultSource entity.Source) *ProjectManager {
defaultSource entity.Source,
) *ProjectManager {
return &ProjectManager{
projectRepo: projectRepo,
organizationRepo: organizationRepo,
Expand Down
4 changes: 1 addition & 3 deletions pkg/server/manager/stack/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func (m *StackManager) BuildStackFilter(ctx context.Context, orgIDParam, project
if err != nil {
return nil, err
}
filter.ProjectID = uint(projectEntity.ID)
filter.ProjectID = projectEntity.ID
if envParam != "" {
if cloudParam != "" {
// if cloud is present, use project name, cloud and environment to derive the deployable stack under clouds path
Expand Down Expand Up @@ -277,7 +277,6 @@ func convertV1ResourceToEntity(resource *v1.Resource) (*entity.Resource, error)
// Determine resource plane and resource type based on meta type
switch resourceTypeMeta {
case v1.Kubernetes:
resourceTypeMeta = v1.Kubernetes
resourcePlane = string(v1.Kubernetes)
// if this is Kubernetes resource, resource type is apiVersion/kind, resource name is namespace/name
resourceType = fmt.Sprintf("%s/%s", idParts[0], idParts[1])
Expand All @@ -287,7 +286,6 @@ func convertV1ResourceToEntity(resource *v1.Resource) (*entity.Resource, error)
resourceName = fmt.Sprintf("%s/%s", idParts[2], idParts[3])
}
case v1.Terraform:
resourceTypeMeta = v1.Terraform
// Get provider info for terraform resources
if providerInfo, ok := resource.Extensions["provider"].(string); ok {
resourceProvider = providerInfo
Expand Down
3 changes: 2 additions & 1 deletion pkg/server/manager/workspace/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ type WorkspaceManager struct {

func NewWorkspaceManager(workspaceRepo repository.WorkspaceRepository,
backendRepo repository.BackendRepository,
defaultBackend entity.Backend) *WorkspaceManager {
defaultBackend entity.Backend,
) *WorkspaceManager {
return &WorkspaceManager{
workspaceRepo: workspaceRepo,
backendRepo: backendRepo,
Expand Down
8 changes: 4 additions & 4 deletions pkg/server/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ func TokenAuthMiddleware(keyMap map[string]any, whitelist []string, logFilePath
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Use the proper key to verify the token
logger := GetMiddlewareLogger(r.Context(), logFilePath)
token_string := jwtauth.TokenFromHeader(r)
t, err := jwt.Parse(token_string, func(tok *jwt.Token) (interface{}, error) {
tokenString := jwtauth.TokenFromHeader(r)
t, err := jwt.Parse(tokenString, func(tok *jwt.Token) (interface{}, error) {
// Get the kid from the token header
kid, ok := tok.Header["kid"].(string)
if !ok {
Expand Down Expand Up @@ -71,10 +71,10 @@ func TokenAuthMiddleware(keyMap map[string]any, whitelist []string, logFilePath
}
}

func SubjectWhitelisted(subject, org_type, org_name string, whitelist []string) bool {
func SubjectWhitelisted(subject, orgType, orgName string, whitelist []string) bool {
// iterate through whitelist and return true of any matches with subject
for _, whitelistedItem := range whitelist {
if subject == whitelistedItem || (org_type == "application" && org_name == whitelistedItem) {
if subject == whitelistedItem || (orgType == "application" && orgName == whitelistedItem) {
return true
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
var APILoggerKey = &contextKey{"logger"}

func InitLogger(logFilePath string, name string) *httplog.Logger {
logWriter, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
logWriter, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
if err != nil {
klog.Fatalf("Failed to open log file: %v", err)
}
Expand Down
24 changes: 16 additions & 8 deletions pkg/server/middleware/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,29 @@ import (
)

// Key to use when setting the trace ID and user ID.
type ctxKeyTraceID int
type ctxKeyUserID string
type (
ctxKeyTraceID int
ctxKeyUserID string
)

// TraceIDKey and UserIDKey are the keys that hold the unique
// trace ID and user ID in a request context.
const TraceIDKey ctxKeyTraceID = 0
const UserIDKey ctxKeyUserID = "user_id"
const (
TraceIDKey ctxKeyTraceID = 0
UserIDKey ctxKeyUserID = "user_id"
)

// TraceIDHeader and UserIDHeader is the name of the HTTP Header
// which contains the trace id and user id.
var TraceIDHeader = "x-kusion-trace"
var UserIDHeader = "x-kusion-user"
var (
TraceIDHeader = "x-kusion-trace"
UserIDHeader = "x-kusion-user"
)

var prefix string
var reqid uint64
var (
prefix string
reqid uint64
)

// A quick note on the statistics here: we're trying to calculate the chance that
// two randomly generated base62 prefixes will collide. We use the formula from
Expand Down
6 changes: 4 additions & 2 deletions pkg/server/util/auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func GetJWKSMapFromIAM(ctx context.Context, keyType string) (map[string]any, err
}

resp, body, err := httputil.ProcessResponse(ctx, req)
defer func() { _ = resp.Body.Close() }()
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -76,7 +77,7 @@ func GetJWKSMapFromIAM(ctx context.Context, keyType string) (map[string]any, err
return keyMap, nil
}

func VerifyJWTToken(ctx context.Context, token_string string) (string, error) {
func VerifyJWTToken(ctx context.Context, tokenString string) (string, error) {
logger := logutil.GetLogger(ctx)
ErrKID := errors.New("the JWT has an invalid kid")
keyMap, err := GetJWKSMapFromIAM(ctx, "RSA")
Expand All @@ -85,7 +86,7 @@ func VerifyJWTToken(ctx context.Context, token_string string) (string, error) {
}

// Use the proper key to verify the token
token, err := jwt.Parse(token_string, func(tok *jwt.Token) (interface{}, error) {
token, err := jwt.Parse(tokenString, func(tok *jwt.Token) (interface{}, error) {
// Get the kid from the token header.
kidInter, ok := tok.Header["kid"]
if !ok {
Expand Down Expand Up @@ -135,6 +136,7 @@ func GenerateIAMToken(ctx context.Context) (string, error) {
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, body, err := httputil.ProcessResponse(ctx, req)
defer func() { _ = resp.Body.Close() }()
if err != nil {
return "", err
}
Expand Down

0 comments on commit 7b36317

Please sign in to comment.