Skip to content

Commit

Permalink
Merge pull request #87 from sdslabs/magnus_major
Browse files Browse the repository at this point in the history
Fixing the broken
  • Loading branch information
ashpect authored Jun 2, 2024
2 parents 3675637 + 92eab84 commit da3a432
Show file tree
Hide file tree
Showing 27 changed files with 469 additions and 88 deletions.
5 changes: 5 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"foxundermoon.shell-format"
]
}
3 changes: 2 additions & 1 deletion challenges-sample/the-varsity/challenge-checker/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ def check_route():
result["status"] = status
except Exception as e:
logging.error(f"Error checking challenge: {str(e)}")
result["error"] = str(e)
# result["error"] = str(e)
result["status"] = 0
results["data"].append(result)
return jsonify(results)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def check_challenge(url):
result = {}

register_response = requests.post(
url + "register", json={"username": "something", "voucher": ""}
url + "register", json={"username": "something", "voucher": ""}, timeout=2
)

# Check if the request was successful (status code 200)
Expand All @@ -31,7 +31,7 @@ def check_challenge(url):
article_data = {"issue": "5"}

article_response = requests.post(
url + "article", json=article_data, headers=article_headers
url + "article", json=article_data, headers=article_headers, timeout=2
)

if article_response.status_code == 200:
Expand Down
Empty file removed challenges/.gitkeep
Empty file.
6 changes: 3 additions & 3 deletions config.sample.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
kubeconfig = ""
kubeconfig = "/home/darkhood148/.kube/config"
kubehost = "0.0.0.0"
backendurl = "http://10.25.1.15:15528"
backendurl = "http://10.25.1.15:3000"
kubenamespace = "default"
timeout = 20 # in seconds

Expand All @@ -19,7 +19,7 @@ templated_manifests = [

[services.api]
host = "0.0.0.0"
port = 15528
port = 3000

[teamvm]
teampodname = "katana-team-master-pod"
Expand Down
1 change: 1 addition & 0 deletions docs/themes/hugo-geekdoc
Submodule hugo-geekdoc added at c420c6
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/go-sql-driver/mysql v1.7.1
github.com/gofiber/fiber/v2 v2.48.0
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/mholt/archiver/v3 v3.5.1
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
github.com/sirupsen/logrus v1.9.3
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
Expand Down
6 changes: 4 additions & 2 deletions lib/deployment/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,10 @@ func DeployCluster(kubeconfig *rest.Config, kubeclientset *kubernetes.Clientset)

clientset, _ := utils.GetKubeClient()

nodes, _ := utils.GetNodes(clientset)

nodes, err := utils.GetNodes(clientset)
if err != nil {
log.Println(err)
}
deploymentConfig.NodeAffinityValue = nodes[0].Name

for _, m := range clusterConfig.TemplatedManifests {
Expand Down
8 changes: 2 additions & 6 deletions lib/mongo/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,13 @@ var link *mongo.Database

func setupAdmin() error {
adminUser := configs.AdminConfig
pwd, err := utils.HashPassword(adminUser.Password)
if err != nil {
return fmt.Errorf("cannot hash password: %w", err)
}

pwd := utils.SHA256(adminUser.Password)
admin := types.AdminUser{
Username: adminUser.Username,
Password: pwd,
}

if _, err = AddAdmin(context.Background(), admin); err != nil {
if _, err := AddAdmin(context.Background(), admin); err != nil {
return fmt.Errorf("cannot add admin: %w", err)
} else {
log.Printf("admin privileges have been given to username: %s", admin.Username)
Expand Down
11 changes: 11 additions & 0 deletions lib/mongo/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"

"github.com/sdslabs/katana/types"
"go.mongodb.org/mongo-driver/bson"
)

func InsertOne(ctx context.Context, collectionName string, data interface{}) (interface{}, error) {
Expand Down Expand Up @@ -31,3 +32,13 @@ func CreateTeams(teams []interface{}) (interface{}, error) {
func AddAdmin(ctx context.Context, admin types.AdminUser) (interface{}, error) {
return InsertOne(ctx, AdminCollection, admin)
}

func AddChallenge(challenge types.Challenge, teamName string) error {
teamFilter := bson.M{"username": teamName}
update := bson.M{"$push": bson.M{"challenges": challenge}}
_, err := link.Collection(TeamsCollection).UpdateOne(context.TODO(), teamFilter, update)
if err != nil {
return err
}
return nil
}
4 changes: 0 additions & 4 deletions lib/mongo/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,3 @@ func UpdateOne(ctx context.Context, collectionName string, filter bson.M, data i
collection := link.Collection(collectionName)
return collection.FindOneAndUpdate(ctx, filter, bson.M{"$set": data}, option).Err()
}

func UpsertOne(ctx context.Context, collectionName string, filter bson.M, data interface{}) error {
return UpdateOne(ctx, collectionName, filter, data, options.FindOneAndUpdate().SetUpsert(true))
}
2 changes: 1 addition & 1 deletion lib/mysql/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func setup() error {

func setupGogs() error {
if err := CreateDatabase(gogsDatabase); err != nil {
fmt.Errorf("cannot create database: %w", err)
log.Println("cannot create database: %w", err)
}
if err := CreateGogsAdmin(configs.AdminConfig.Username, configs.AdminConfig.Password); err != nil {
fmt.Errorf("cannot create gogs admin: %w", err)
Expand Down
71 changes: 71 additions & 0 deletions lib/retrieve_data/jsonSaver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package retrieve_data

import (
"context"
"encoding/json"
"fmt"
"os"
"time"

"github.com/sdslabs/katana/lib/mongo"
"github.com/sdslabs/katana/lib/utils"
"go.mongodb.org/mongo-driver/bson"
)

var ticker *time.Ticker
var tick int

func saveJSON() {
for range ticker.C {
data := mongo.FetchDocs(context.Background(), "teams", bson.M{})
path := fmt.Sprintf("./json_data/data-tick-%d.json", tick)
jsonData, err := convertBSONArrayToJSONArray(data)
if err != nil {
fmt.Println(err)
return
}
storeJSONToFile(jsonData, path)
tick++
}
}

func StartSaving() {
ticker = utils.GetTicker()
utils.CreateDirectoryIfNotExists("json_data")
go saveJSON()
}

func convertBSONArrayToJSONArray(bsonArray []bson.M) ([]byte, error) {
var jsonArray []map[string]interface{}

for _, bsonDoc := range bsonArray {
delete(bsonDoc, "publicKey")
delete(bsonDoc, "password")

jsonArray = append(jsonArray, bsonDoc)
}

jsonData, err := json.Marshal(jsonArray)
if err != nil {
return nil, fmt.Errorf("failed to marshal JSON array: %w", err)
}

return jsonData, nil
}

func storeJSONToFile(jsonData []byte, filePath string) error {
jsonMap := map[string]interface{}{"data": json.RawMessage(jsonData)}

finalJSONData, err := json.MarshalIndent(jsonMap, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal final JSON: %w", err)
}

err = os.WriteFile(filePath, finalJSONData, 0644)
if err != nil {
return fmt.Errorf("failed to write JSON to file: %w", err)
}

fmt.Printf("JSON data stored in file: %s\n", filePath)
return nil
}
11 changes: 7 additions & 4 deletions lib/utils/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,13 @@ func HashPassword(password string) (string, error) {
}

func CompareHashWithPassword(hashedPassword, password string) bool {
hash := []byte(hashedPassword)
pass := []byte(password)
err := bcrypt.CompareHashAndPassword(hash, pass)
return err == nil

pass := SHA256(password)
if pass == hashedPassword {
return true;
}else{
return false
}
}

// EncodePassword encodes password using PBKDF2 SHA256 with given salt.
Expand Down
11 changes: 4 additions & 7 deletions lib/utils/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,23 +104,20 @@ func TestHashPassword(t *testing.T) {
func TestCompareHashWithPassword(t *testing.T) {
// Generate a hash from a password
password := "myStrongPassword123"
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
t.Fatalf("Error generating hash: %v", err)
}
hashedPassword := SHA256(password)

// Test case 1: Hash matches the original password
if !CompareHashWithPassword(string(hashedPassword), password) {
if !CompareHashWithPassword(hashedPassword, password) {
t.Error("Hash and password should match")
}

// Test case 2: Hash does not match the original password
if CompareHashWithPassword(string(hashedPassword), "wrongPassword") {
if CompareHashWithPassword(hashedPassword, "wrongPassword") {
t.Error("Hash and wrong password should not match")
}

// Test case 3: Empty password
if CompareHashWithPassword(string(hashedPassword), "") {
if CompareHashWithPassword(hashedPassword, "") {
t.Error("Hash and empty password should not match")
}
}
Expand Down
3 changes: 2 additions & 1 deletion lib/utils/kube.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -150,7 +151,7 @@ func CopyFromPod(podName string, containerName string, pathInPod string, localFi
TTY: false,
}, scheme.ParameterCodec)

exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
exec, err := remotecommand.NewSPDYExecutor(config, http.MethodPost, req.URL())
if err != nil {
log.Printf("Error creating executor: %s\n", err)
return err
Expand Down
15 changes: 15 additions & 0 deletions lib/utils/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,21 @@ func RunCommand(cmd string) error {
return nil
}

func CreateDirectoryIfNotExists(dirPath string) error {
if _, err := os.Stat(dirPath); !os.IsNotExist(err) {
if err := os.RemoveAll(dirPath); err != nil {
return fmt.Errorf("failed to delete existing directory: %w", err)
}
fmt.Printf("Directory '%s' deleted.\n", dirPath)
}

if err := os.MkdirAll(dirPath, 0755); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
fmt.Printf("Directory '%s' created.\n", dirPath)
return nil
}

func GetKatanaRootPath() (string, error) {
katanaDir, err := os.Getwd()
if err != nil {
Expand Down
31 changes: 31 additions & 0 deletions lib/utils/ticker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package utils

import (
"time"
)

var Ticker *time.Ticker

func InitTicker(duration time.Duration) {
Ticker = time.NewTicker(duration)
}

func GetTicker() *time.Ticker {
return Ticker
}

func SetTicker(ticker *time.Ticker) {
Ticker = ticker
}

func StopTicker() {
Ticker.Stop()
}

func ResetTicker(duration time.Duration) {
Ticker.Reset(duration)
}

func GetRemainingTimeBeforeNextTick() time.Duration {
return time.Until(<-Ticker.C)
}
Loading

0 comments on commit da3a432

Please sign in to comment.