Skip to content

Commit 731280b

Browse files
authored
Merge pull request #273 from sdslabs/challengeUpdate
Add functionality to update challenge at startup and fix authentication error
2 parents 9a4ba4a + f07b660 commit 731280b

File tree

14 files changed

+122
-50
lines changed

14 files changed

+122
-50
lines changed

api/info.go

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,13 @@ func challengeInfoHandler(c *gin.Context) {
7070
return
7171
}
7272

73-
var challSolves int
74-
var challengeUser []UserSolveResp
73+
challengePorts := make([]uint32, len(challenge.Ports))
74+
for index, port := range challenge.Ports {
75+
challengePorts[index] = port.PortNo
76+
}
7577

78+
var challSolves int
79+
challengeUser := make([]UserSolveResp, 0)
7680
for _, user := range users {
7781
if user.Role == core.USER_ROLES["contestant"] {
7882
userResp := UserSolveResp{
@@ -91,7 +95,7 @@ func challengeInfoHandler(c *gin.Context) {
9195
Category: challenge.Type,
9296
CreatedAt: challenge.CreatedAt,
9397
Status: challenge.Status,
94-
Ports: challenge.Ports,
98+
Ports: challengePorts,
9599
Hints: challenge.Hints,
96100
Desc: challenge.Description,
97101
Points: challenge.Points,
@@ -137,8 +141,13 @@ func availableChallengeInfoHandler(c *gin.Context) {
137141
return
138142
}
139143

144+
challengePorts := make([]uint32, len(challenge.Ports))
145+
for index, port := range challenge.Ports {
146+
challengePorts[index] = port.PortNo
147+
}
148+
140149
var challSolves int
141-
var challengeUser []UserSolveResp
150+
challengeUser := make([]UserSolveResp, 0)
142151

143152
for _, user := range users {
144153
if user.Role == core.USER_ROLES["contestant"] {
@@ -158,7 +167,7 @@ func availableChallengeInfoHandler(c *gin.Context) {
158167
Category: challenge.Type,
159168
CreatedAt: challenge.CreatedAt,
160169
Status: challenge.Status,
161-
Ports: challenge.Ports,
170+
Ports: challengePorts,
162171
Hints: challenge.Hints,
163172
Desc: challenge.Description,
164173
Points: challenge.Points,
@@ -395,15 +404,15 @@ func userInfoHandler(c *gin.Context) {
395404
}
396405

397406
userChallenges := make([]ChallengeSolveResp, len(challenges))
398-
for _, challenge := range challenges {
407+
for index, challenge := range challenges {
399408
challResp := ChallengeSolveResp{
400409
Id: challenge.ID,
401410
Name: challenge.Name,
402411
Category: challenge.Type,
403412
SolvedAt: challenge.CreatedAt,
404413
Points: challenge.Points,
405414
}
406-
userChallenges = append(userChallenges, challResp)
415+
userChallenges[index] = challResp
407416
}
408417

409418
rank, err := database.GetUserRank(parsedUserId, user.Score, user.UpdatedAt)
@@ -470,7 +479,7 @@ func submissionsHandler(c *gin.Context) {
470479
})
471480
return
472481
}
473-
var submissionsResp []SubmissionResp
482+
submissionsResp := make([]SubmissionResp, 0)
474483

475484
for _, submission := range submissions {
476485
user, err := database.QueryUserById(submission.UserID)

api/manage.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package api
33
import (
44
"fmt"
55
"net/http"
6+
"os"
67
"path/filepath"
78
"strings"
89
"time"
@@ -360,7 +361,8 @@ func manageScheduledAction(c *gin.Context) {
360361

361362
// Prepare challenge info from .tar file.
362363
// @Summary Untar and fetch info from beast.toml file in challenge
363-
// @Description Handles the challenge management from a challenge in tar file
364+
// @Description Handles the challenge management from a challenge in tar file. Currently prepare the tar file
365+
// by running `tar cvf chall_dir.tar .` inside the chall_dir.
364366
// @Tags manage
365367
// @Accept json
366368
// @Produce json
@@ -380,6 +382,14 @@ func manageUploadHandler(c *gin.Context) {
380382
return
381383
}
382384

385+
if err = utils.CreateIfNotExistDir(core.BEAST_TEMP_DIR); err != nil {
386+
if err := os.MkdirAll(core.BEAST_TEMP_DIR, 0755); err != nil {
387+
c.JSON(http.StatusInternalServerError, HTTPErrorResp{
388+
Error: fmt.Sprintf("Could not create dir %s: %s", core.BEAST_TEMP_DIR, err),
389+
})
390+
}
391+
}
392+
383393
tarContextPath := filepath.Join(core.BEAST_TEMP_DIR, file.Filename)
384394

385395
// The file is received, save it
@@ -436,7 +446,7 @@ func manageUploadHandler(c *gin.Context) {
436446

437447
c.JSON(http.StatusOK, ChallengePreviewResp{
438448
Name: config.Challenge.Metadata.Name,
439-
Category: config.Challenge.Metadata.Tags,
449+
Category: config.Challenge.Metadata.Type,
440450
Ports: config.Challenge.Env.Ports,
441451
Hints: config.Challenge.Metadata.Hints,
442452
Desc: config.Challenge.Metadata.Description,

api/response.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ package api
22

33
import (
44
"time"
5-
6-
"github.com/sdslabs/beastv4/core/database"
75
)
86

97
type HTTPPlainResp struct {
@@ -100,7 +98,7 @@ type ChallengeInfoResp struct {
10098
Category string `json:"category" example:"web"`
10199
CreatedAt time.Time `json:"createdAt"`
102100
Status string `json:"status" example:"deployed"`
103-
Ports []database.Port `json:"ports" example:[3001, 3002]`
101+
Ports []uint32 `json:"ports" example:[3001, 3002]`
104102
Hints string `json:"hints" example:Try robots`
105103
Desc string `json:"description" example:A simple web challenge`
106104
Points uint `json:"points" example:"50"`
@@ -110,7 +108,7 @@ type ChallengeInfoResp struct {
110108

111109
type ChallengePreviewResp struct {
112110
Name string `json:"name" example:"Web Challenge"`
113-
Category []string `json:"category" example:"web"`
111+
Category string `json:"category" example:"web"`
114112
Ports []uint32 `json:"ports" example:[3001, 3002]`
115113
Hints []string `json:"hints" example:Try robots`
116114
Desc string `json:"description" example:A simple web challenge`

api/router.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ func initGinRouter() *gin.Engine {
3434
authGroup.POST("/reset-password", authorize, resetPasswordHandler)
3535
}
3636

37+
// For serving static files
38+
router.StaticFile("/api/info/logo", getLogoPath())
39+
router.GET("/api/info/competition-info", competitionInfoHandler)
40+
3741
// API routes group
3842
apiGroup := router.Group("/api", authorize)
3943
{
@@ -71,9 +75,6 @@ func initGinRouter() *gin.Engine {
7175
infoGroup.POST("/user", userInfoHandler)
7276
infoGroup.GET("/user/available", getAllUsersInfoHandler)
7377
infoGroup.POST("/submissions", submissionsHandler)
74-
infoGroup.GET("/competition-info", competitionInfoHandler)
75-
// For serving static files
76-
infoGroup.StaticFile("/logo", getLogoPath())
7778
}
7879

7980
// Notification route group

core/database/challenges.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ func QueryAllChallenges() ([]Challenge, error) {
9494
DBMux.Lock()
9595
defer DBMux.Unlock()
9696

97-
tx := Db.Find(&challenges)
97+
tx := Db.Preload("Ports").Find(&challenges)
9898

9999
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
100100
return nil, nil
@@ -113,7 +113,7 @@ func QueryChallengeEntries(key string, value string) ([]Challenge, error) {
113113
DBMux.Lock()
114114
defer DBMux.Unlock()
115115

116-
tx := Db.Where(queryKey, value).Find(&challenges)
116+
tx := Db.Preload("Ports").Where(queryKey, value).Find(&challenges)
117117
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
118118
return nil, nil
119119
}

core/database/ports.go

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package database
22

33
import (
4-
"errors"
54
"fmt"
65

76
"github.com/jinzhu/gorm"
@@ -19,9 +18,7 @@ type Port struct {
1918
// It returns an error if anything wrong happen during the
2019
// transaction. If the entry already exists then it does not
2120
// do anything and returns.
22-
func PortEntryGetOrCreate(port Port) (Port, error) {
23-
var portEntry Port
24-
21+
func PortEntryGetOrCreate(port *Port) (Port, error) {
2522
DBMux.Lock()
2623
defer DBMux.Unlock()
2724

@@ -31,22 +28,13 @@ func PortEntryGetOrCreate(port Port) (Port, error) {
3128
return Port{}, fmt.Errorf("Error while starting transaction : %s", tx.Error)
3229
}
3330

34-
err := tx.Where("port_no = ?", port.PortNo).First(&portEntry)
35-
36-
if !errors.Is(err.Error, gorm.ErrRecordNotFound) {
37-
if err := tx.Create(&port).Error; err != nil {
38-
tx.Rollback()
39-
return Port{}, err
40-
}
41-
42-
return port, tx.Commit().Error
43-
}
44-
45-
if tx.Error != nil {
46-
return Port{}, fmt.Errorf("Error while port get for check : %s", tx.Error)
31+
err := tx.FirstOrCreate(port, *port).Error
32+
if err != nil {
33+
tx.Rollback()
34+
return Port{}, err
4735
}
4836

49-
return portEntry, tx.Commit().Error
37+
return *port, tx.Commit().Error
5038
}
5139

5240
func GetAllocatedPorts(challenge Challenge) ([]Port, error) {

core/database/user.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ type User struct {
2828

2929
Challenges []*Challenge `gorm:"many2many:user_challenges;"`
3030
Name string `gorm:"not null"`
31-
Email string `gorm:"non null";unique`
31+
Email string `gorm:"non null;unique"`
3232
SshKey string
3333
Status uint `gorm:"not null;default:0"` // 0 for unbanned, 1 for banned
3434
Score uint `gorm:"default:0"`

core/manager/challenge.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -534,18 +534,21 @@ func undeployChallenge(challengeName string, purge bool) error {
534534
}
535535

536536
func StartUndeployChallenge(challengeName string, purge bool) error {
537+
var sendNotificationError error
537538
err := undeployChallenge(challengeName, purge)
538539
if err != nil {
539540
msg := fmt.Sprintf("UNDEPLOY ERROR: %s : %s", challengeName, err)
540541
log.Error(msg)
541-
notify.SendNotification(notify.Error, msg)
542+
sendNotificationError = notify.SendNotification(notify.Error, msg)
542543
} else {
543544
msg := fmt.Sprintf("UNDEPLOY SUCCESSFUL: %s", challengeName)
544545
log.Info(msg)
545-
notify.SendNotification(notify.Success, msg)
546+
sendNotificationError = notify.SendNotification(notify.Success, msg)
546547
}
547548

548-
log.Info("Notification for the event sent.")
549+
if sendNotificationError == nil {
550+
log.Info("Notification for the event sent.")
551+
}
549552
return err
550553
}
551554

core/manager/pipeline.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ func bootstrapDeployPipeline(challengeDir string, skipStage bool, skipCommit boo
321321
}
322322

323323
// Using the challenge dir we got, update the database entries for the challenge.
324-
err = updateOrCreateChallengeDbEntry(&challenge, config)
324+
err = UpdateOrCreateChallengeDbEntry(&challenge, config)
325325
if err != nil {
326326
log.Errorf("An error occured while creating db entry for challenge :: %s", challengeName)
327327
log.Errorf("Db error : %s", err)
@@ -427,14 +427,17 @@ func bootstrapDeployPipeline(challengeDir string, skipStage bool, skipCommit boo
427427
// notifications to slack on the basis of the result of the deploy pipeline.
428428
func StartDeployPipeline(challengeDir string, skipStage bool, skipCommit bool) {
429429
challengeName := filepath.Base(challengeDir)
430+
var sendNotificationError error
430431

431432
err := bootstrapDeployPipeline(challengeDir, skipStage, skipCommit)
432433
if err != nil {
433-
notify.SendNotification(notify.Error, err.Error())
434+
sendNotificationError = notify.SendNotification(notify.Error, err.Error())
434435
} else {
435436
msg := fmt.Sprintf("DEPLOY SUCCESS : %s : Challenge deployment pipeline successful.", challengeName)
436-
notify.SendNotification(notify.Success, msg)
437+
sendNotificationError = notify.SendNotification(notify.Success, msg)
437438
}
438439

439-
log.Debugf("%s: Notification sent", challengeName)
440+
if sendNotificationError == nil {
441+
log.Debugf("%s: Notification sent", challengeName)
442+
}
440443
}

core/manager/sync.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ func SyncBeastRemote() error {
6969
}
7070
log.Info("Beast git base synced with remote")
7171
go config.UpdateUsedPortList()
72+
UpdateChallenges()
7273
return fmt.Errorf(strings.Join(errStrings, "\n"))
7374
}
7475

0 commit comments

Comments
 (0)