Skip to content

Commit

Permalink
grader: check authenticity of submitting user
Browse files Browse the repository at this point in the history
Signed-off-by: Benedict Schlueter <[email protected]>
  • Loading branch information
benschlueter committed Oct 14, 2024
1 parent ab757e3 commit 1c5a6f0
Show file tree
Hide file tree
Showing 12 changed files with 169 additions and 156 deletions.
80 changes: 35 additions & 45 deletions grader/gradeapi/gradeapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,47 @@ import (
"context"
"fmt"
"net"
"os"
"path"

"github.com/benschlueter/delegatio/grader/gradeapi/gradeproto"
"github.com/benschlueter/delegatio/internal/config"
"github.com/benschlueter/delegatio/internal/k8sapi"
"github.com/benschlueter/delegatio/internal/store"
"github.com/benschlueter/delegatio/internal/storewrapper"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

// API is the API.
type API struct {
logger *zap.Logger
dialer Dialer
logger *zap.Logger
dialer Dialer
client *k8sapi.Client
backingStore store.Store

gradeproto.UnimplementedAPIServer
}

// New creates a new API.
func New(logger *zap.Logger, dialer Dialer) (*API, error) {
func New(logger *zap.Logger, dialer Dialer, initStore bool) (*API, error) {
// use the current context in kubeconfig
client, err := k8sapi.NewClient(logger)
if err != nil {
return nil, err
}
var store store.Store
if initStore {
store, err = client.GetStore()

Check failure on line 41 in grader/gradeapi/gradeapi.go

View workflow job for this annotation

GitHub Actions / test

client.GetStore undefined (type *k8sapi.Client has no field or method GetStore)
if err != nil {
return nil, err
}
}

return &API{
logger: logger,
dialer: dialer,
logger: logger,
dialer: dialer,
client: client,
backingStore: store,
}, nil
}

Expand All @@ -52,44 +71,14 @@ func (a *API) grpcWithDialer() grpc.DialOption {
})
}

func (a *API) readFile(fileName string) ([]byte, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer file.Close()

if _, err := file.Seek(0, 0); err != nil {
return nil, err
}
fileInfo, _ := file.Stat()
fileSize := fileInfo.Size()
bytes := make([]byte, fileSize)
if _, err := file.Read(bytes); err != nil {
return nil, err
}
return bytes, nil
func (a *API) data() storewrapper.StoreWrapper {
return storewrapper.StoreWrapper{Store: a.backingStore}
}

// SendGradingRequest sends a grading request to the grader service.
func (a *API) SendGradingRequest(ctx context.Context, fileName string) (int, error) {
f, err := os.CreateTemp("/tmp", "gradingRequest-")
if err != nil {
return 0, err
}
defer os.Remove(f.Name())
defer f.Close()
// against a race condition
if err := f.Sync(); err != nil {
return 0, err
}

_, nonceName := path.Split(f.Name())
a.logger.Info("create nonce file", zap.String("file", nonceName))

fileBytes, err := a.readFile(fileName)
if err != nil {
a.logger.Error("failed to read file", zap.String("file", fileName), zap.Error(err))
func (a *API) SendGradingRequest(ctx context.Context, fileBytes []byte, signature []byte, studentID string) (int, error) {
if studentID == "" {
return 0, fmt.Errorf("studentID is empty")
}

conn, err := a.dialInsecure(ctx, fmt.Sprintf("grader-service.%s.svc.cluster.local:%d", config.GraderNamespaceName, config.GradeAPIport))
Expand All @@ -98,9 +87,10 @@ func (a *API) SendGradingRequest(ctx context.Context, fileName string) (int, err
}
client := gradeproto.NewAPIClient(conn)
resp, err := client.RequestGrading(ctx, &gradeproto.RequestGradingRequest{
Id: 1,
Nonce: nonceName,
Solution: fileBytes,
ExerciseId: 1,
Solution: fileBytes,
Signature: signature,
StudentId: studentID,
})
if err != nil {
return 0, err
Expand Down
73 changes: 42 additions & 31 deletions grader/gradeapi/gradeproto/gradeapi.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions grader/gradeapi/gradeproto/gradeapi.proto
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ service API {
}

message RequestGradingRequest {
int32 id = 1;
string nonce = 2;
int32 exerciseId = 1;
string studentId = 2;
bytes solution = 3;
bool submit = 4;
bytes signature = 4;
bool submit = 5;
}

message RequestGradingResponse {
int32 points = 1;
bytes log = 2;
}
}
6 changes: 3 additions & 3 deletions grader/gradeapi/graders/graders.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
// of the graders. Currently we do not need any state.
type Graders struct {
logger *zap.Logger
studentID string
UUID string
singleExecTimeout time.Duration
totalExecTimeout time.Duration
}
Expand All @@ -32,7 +32,7 @@ type Graders struct {
func NewGraders(zapLogger *zap.Logger, studentID string) (*Graders, error) {
c := &Graders{
logger: zapLogger,
studentID: studentID,
UUID: studentID,
singleExecTimeout: time.Second,
totalExecTimeout: 15 * time.Second,
}
Expand Down Expand Up @@ -69,7 +69,7 @@ func (g *Graders) executeCommand(ctx context.Context, fileName string, arg ...st
func (g *Graders) writeFileToDisk(_ context.Context, solution []byte) (*os.File, error) {
f, err := os.CreateTemp(
filepath.Join(config.SandboxPath, "tmp"),
fmt.Sprintf("solution-%s-%v", g.studentID, "now" /*time.Now().Format(time.RFC822)*/),
fmt.Sprintf("solution-%s-%v", g.UUID, "now" /*time.Now().Format(time.RFC822)*/),
)
if err != nil {
g.logger.Error("failed to create content file", zap.Error(err))
Expand Down
49 changes: 37 additions & 12 deletions grader/gradeapi/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ package gradeapi

import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha512"

"github.com/benschlueter/delegatio/grader/gradeapi/gradeproto"
"github.com/benschlueter/delegatio/grader/gradeapi/graders"
"github.com/benschlueter/delegatio/internal/config"
"go.uber.org/zap"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
Expand All @@ -25,29 +30,25 @@ func (a *API) RequestGrading(ctx context.Context, in *gradeproto.RequestGradingR
var points int
var log []byte
var err error
uuid := in.GetStudentId()
/*
* How to authenticate the user?
* The user signs the request with a private key and the server verifies the signature
*/
/* p, _ := peer.FromContext(ctx)
requestEndpoint := p.Addr.String() */
// ToDO: use a unique ID from the USER
if in.GetSubmit() {
a.logger.Info("received grading request; verifying identity")
a.logger.Debug("nonce check passed", zap.String("nonce", in.GetNonce()))
// TODO: Verify identity
if err := a.checkNonce(ctx, in.GetNonce()); err != nil {
return nil, status.Error(codes.Unauthenticated, "nonce check failed")
}
a.logger.Info("received grading request; verifying identity")
if err := a.checkSignature(ctx, uuid, in.GetSignature(), in.GetSolution()); err != nil {
return nil, err
}
toImplementName := "bschlueter"

grader, err := graders.NewGraders(a.logger.Named(toImplementName), toImplementName)
grader, err := graders.NewGraders(a.logger.Named(uuid), uuid)
if err != nil {
a.logger.Error("failed to create graders", zap.Error(err))
}

switch id := in.GetId(); id {
switch id := in.GetExerciseId(); id {
case 1:
a.logger.Info("received grading request for id 1")
points, log, err = grader.GradeExerciseType1(ctx, in.GetSolution(), 1)
Expand All @@ -58,13 +59,37 @@ func (a *API) RequestGrading(ctx context.Context, in *gradeproto.RequestGradingR
a.logger.Info("received grading request for id 2")
}

if err := a.updatePointsUser(ctx, points, toImplementName); err != nil {
if err := a.updatePointsUser(ctx, points, uuid); err != nil {
return nil, status.Error(codes.Internal, "failed to update points")
}

return &gradeproto.RequestGradingResponse{Points: int32(points), Log: log}, nil
}

func (a *API) checkNonce(_ context.Context, _ string) error {
func (a *API) checkSignature(_ context.Context, UUID string, signature, solution []byte) error {
a.logger.Info("checking signature", zap.String("studentID", UUID))
exists, err := a.data().UUIDExists(UUID)
if err != nil {
return err
}
if !exists {
return status.Error(codes.NotFound, "user not found")
}
var userData config.UserInformation
if err := a.data().GetUUIDData(UUID, &userData); err != nil {
return status.Error(codes.FailedPrecondition, "failed to get user data")
}
a.logger.Info("got user data", zap.String("publicKey", string(userData.PubKey)))
sshPubKey, err := ssh.ParsePublicKey(userData.PubKey)
if err != nil {
return status.Error(codes.Internal, "failed to unmarshal public key")
}
pubKeyNewIface := sshPubKey.(ssh.CryptoPublicKey)
pubKewNewIfaceTwo := pubKeyNewIface.CryptoPublicKey()
rsaPubKey := pubKewNewIfaceTwo.(*rsa.PublicKey)
hashSolution := sha512.Sum512(solution)
if err := rsa.VerifyPKCS1v15(rsaPubKey, crypto.SHA512, hashSolution[:], signature); err != nil {
return status.Error(codes.Unauthenticated, "signature check")
}
return nil
}
2 changes: 1 addition & 1 deletion grader/server/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var version = "0.0.0"
func run(dialer gradeapi.Dialer, bindIP, bindPort string, zapLoggerCore *zap.Logger) {
defer func() { _ = zapLoggerCore.Sync() }()
zapLoggerCore.Info("starting delegatio grader", zap.String("version", version), zap.String("commit", config.Commit))
gapi, err := gradeapi.New(zapLoggerCore.Named("gradeapi"), dialer)
gapi, err := gradeapi.New(zapLoggerCore.Named("gradeapi"), dialer, true)
if err != nil {
zapLoggerCore.Fatal("create gradeapi", zap.Error(err))
}
Expand Down
Loading

0 comments on commit 1c5a6f0

Please sign in to comment.