Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OTAC MaxDuration #177

Merged
merged 3 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion generate-protos.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ PROTO_DIR="${PROJECT_PATH}/protos"

docker run --rm \
-v "$(pwd):${PROJECT_PATH}" \
-v "$(pwd)/protos:${PROTO_DIR}" \
-v "$(pwd)/v3/protos:${PROTO_DIR}" \
-w "${PROJECT_PATH}" \
--entrypoint bash \
golang:latest \
Expand Down
24 changes: 22 additions & 2 deletions v3/pkg/accesscode/accesscode.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package accesscode
import (
"context"
"fmt"
"sort"
"time"

hfv1 "github.com/hobbyfarm/gargantua/v3/pkg/apis/hobbyfarm.io/v1"
hfClientset "github.com/hobbyfarm/gargantua/v3/pkg/client/clientset/versioned"
util2 "github.com/hobbyfarm/gargantua/v3/pkg/util"
"sort"
"time"

"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -48,6 +49,25 @@ func (acc AccessCodeClient) GetAccessCodesWithOTACs(codes []string) ([]hfv1.Acce
if err != nil {
return nil, fmt.Errorf("error while retrieving one time access codes %v", err)
}
if otac.Spec.MaxDuration != "" {
otac.Spec.MaxDuration, err = util2.GetDurationWithDays(otac.Spec.MaxDuration)

maxDuration, err := time.ParseDuration(otac.Spec.MaxDuration)
if err != nil {
glog.V(4).Infof("Error parsing OTAC %s MaxDuration '%s': %s", otac.Name, otac.Spec.MaxDuration, err)
continue
}
redeemedTimestamp, err := time.Parse(time.UnixDate, otac.Spec.RedeemedTimestamp)

if err != nil {
return nil, fmt.Errorf("error while parsing redeemedTimestamp time for OTAC %s: %v", otac.Name, err)
}

if time.Now().After(redeemedTimestamp.Add(maxDuration)) { // if the access code is expired don't return any scenarios
glog.V(4).Infof("OTAC %s reached MaxDuration of %s", otac.Name, otac.Spec.MaxDuration)
continue
}
}
codes = append(codes, se.Spec.AccessCode)
}

Expand Down
1 change: 1 addition & 0 deletions v3/pkg/apis/hobbyfarm.io/v1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ type OneTimeAccessCodeList struct {
type OneTimeAccessCodeSpec struct {
User string `json:"user"`
RedeemedTimestamp string `json:"redeemed_timestamp"`
MaxDuration string `json:"max_duration"`
}

// +genclient
Expand Down
34 changes: 30 additions & 4 deletions v3/pkg/authserver/authserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package authserver
import (
"context"
"encoding/json"
"net/http"
"time"

"github.com/hobbyfarm/gargantua/v3/pkg/accesscode"
hfClientset "github.com/hobbyfarm/gargantua/v3/pkg/client/clientset/versioned"
"github.com/hobbyfarm/gargantua/v3/pkg/rbac"
util2 "github.com/hobbyfarm/gargantua/v3/pkg/util"
"net/http"

"github.com/golang/glog"
"github.com/gorilla/mux"
Expand Down Expand Up @@ -38,6 +40,13 @@ func (a AuthServer) SetupRoutes(r *mux.Router) {
glog.V(2).Infof("set up route")
}

type PreparedScheduledEvent struct {
Id string `json:"id"`
Description string `json:"description"`
Name string `json:"name"`
EndDate string `json:"end_timestamp"`
}

func (a AuthServer) ListScheduledEventsFunc(w http.ResponseWriter, r *http.Request) {
user, err := rbac.AuthenticateRequest(r, a.authClient)
if err != nil {
Expand All @@ -46,7 +55,7 @@ func (a AuthServer) ListScheduledEventsFunc(w http.ResponseWriter, r *http.Reque
}

// This holds a map of AC -> SE
accessCodeScheduledEvent := make(map[string]string)
accessCodeScheduledEvent := make(map[string]PreparedScheduledEvent)

// First we add ScheduledEvents based on OneTimeAccessCodes
otacReq, _ := labels.NewRequirement(util2.OneTimeAccessCodeLabel, selection.In, user.GetAccessCodes())
Expand All @@ -63,7 +72,24 @@ func (a AuthServer) ListScheduledEventsFunc(w http.ResponseWriter, r *http.Reque
if err != nil {
continue
}
accessCodeScheduledEvent[otac.Name] = se.Spec.Name
endTime := se.Spec.EndTime

// If OTAC specifies a max Duration we need to calculate the EndTime correctly
if otac.Spec.MaxDuration != "" {
otacEndTime, err := time.Parse(time.UnixDate, otac.Spec.RedeemedTimestamp)
if err != nil {
continue
}
otacDurationWithDays, err := util2.GetDurationWithDays(otac.Spec.MaxDuration)
otacDuration, err := time.ParseDuration(otacDurationWithDays)
if err != nil {
continue
}
otacEndTime = otacEndTime.Add(otacDuration)
endTime = otacEndTime.Format(time.UnixDate)
}

accessCodeScheduledEvent[otac.Name] = PreparedScheduledEvent{se.Name, se.Spec.Description, se.Spec.Name, endTime}
}
}

Expand All @@ -77,7 +103,7 @@ func (a AuthServer) ListScheduledEventsFunc(w http.ResponseWriter, r *http.Reque
glog.Error(err)
continue
}
accessCodeScheduledEvent[ac.Spec.Code] = se.Spec.Name
accessCodeScheduledEvent[ac.Spec.Code] = PreparedScheduledEvent{se.Name, se.Spec.Description, se.Spec.Name, se.Spec.EndTime}
}

encodedMap, err := json.Marshal(accessCodeScheduledEvent)
Expand Down
14 changes: 9 additions & 5 deletions v3/pkg/scheduledeventserver/scheduledevent.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import (
"context"
"encoding/json"
"fmt"
hfv1 "github.com/hobbyfarm/gargantua/v3/pkg/apis/hobbyfarm.io/v1"
hfClientset "github.com/hobbyfarm/gargantua/v3/pkg/client/clientset/versioned"
rbac2 "github.com/hobbyfarm/gargantua/v3/pkg/rbac"
util2 "github.com/hobbyfarm/gargantua/v3/pkg/util"
"net/http"
"strconv"
"strings"
"time"

hfv1 "github.com/hobbyfarm/gargantua/v3/pkg/apis/hobbyfarm.io/v1"
hfClientset "github.com/hobbyfarm/gargantua/v3/pkg/client/clientset/versioned"
rbac2 "github.com/hobbyfarm/gargantua/v3/pkg/rbac"
util2 "github.com/hobbyfarm/gargantua/v3/pkg/util"

"github.com/hobbyfarm/gargantua/v3/protos/authn"
"github.com/hobbyfarm/gargantua/v3/protos/authr"

Expand Down Expand Up @@ -66,7 +67,7 @@ func (s ScheduledEventServer) SetupRoutes(r *mux.Router) {
r.HandleFunc("/a/scheduledevent/new", s.CreateFunc).Methods("POST")
r.HandleFunc("/a/scheduledevent/{id}", s.GetFunc).Methods("GET")
r.HandleFunc("/a/scheduledevent/{id}", s.UpdateFunc).Methods("PUT")
r.HandleFunc("/a/scheduledevent/{id}/otacs/add/{count}", s.GenerateOTACsFunc).Methods("GET")
r.HandleFunc("/a/scheduledevent/{id}/otacs/add/{count}", s.GenerateOTACsFunc).Methods("POST")
r.HandleFunc("/a/scheduledevent/{id}/otacs/delete/{otac}", s.DeleteOTACFunc).Methods("GET")
r.HandleFunc("/a/scheduledevent/{id}/otacs/list", s.GetOTACsFunc).Methods("GET")
r.HandleFunc("/a/scheduledevent/delete/{id}", s.DeleteFunc).Methods("DELETE")
Expand Down Expand Up @@ -700,6 +701,8 @@ func (s ScheduledEventServer) GenerateOTACsFunc(w http.ResponseWriter, r *http.R
return
}

maxDurationValue := r.PostFormValue("max_duration")

scheduledEvent, err := s.hfClientSet.HobbyfarmV1().ScheduledEvents(util2.GetReleaseNamespace()).Get(s.ctx, id, metav1.GetOptions{})
if err != nil {
glog.Error(err)
Expand Down Expand Up @@ -736,6 +739,7 @@ func (s ScheduledEventServer) GenerateOTACsFunc(w http.ResponseWriter, r *http.R
Spec: hfv1.OneTimeAccessCodeSpec{
User: "",
RedeemedTimestamp: "",
MaxDuration: maxDurationValue,
},
}
otac, err = s.hfClientSet.HobbyfarmV1().OneTimeAccessCodes(util2.GetReleaseNamespace()).Create(s.ctx, otac, metav1.CreateOptions{})
Expand Down
23 changes: 21 additions & 2 deletions v3/pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import (
"encoding/json"
"encoding/pem"
"fmt"
mrand "math/rand"

hfv1 "github.com/hobbyfarm/gargantua/v3/pkg/apis/hobbyfarm.io/v1"
hfClientset "github.com/hobbyfarm/gargantua/v3/pkg/client/clientset/versioned"
"github.com/hobbyfarm/gargantua/v3/pkg/client/listers/hobbyfarm.io/v1"
mrand "math/rand"
v1 "github.com/hobbyfarm/gargantua/v3/pkg/client/listers/hobbyfarm.io/v1"

"github.com/golang/glog"
"golang.org/x/crypto/ssh"
Expand Down Expand Up @@ -535,3 +536,21 @@ func GetProtoMarshaller() protojson.MarshalOptions {
func StringPtr(s string) *string {
return &s
}

// This Method converts a given duration into a valid duration for time.ParseDuration.
// time.ParseDuration does not accept "d" for days
func GetDurationWithDays(s string) (string, error) {
// When the duration is given in days, convert it to hours instead as time.ParseDuration does not accept Days
if strings.HasSuffix(s, "d") {
durationWithoutSuffix := strings.TrimSuffix(s, "d")
// string to int
durationDays, err := strconv.Atoi(durationWithoutSuffix)
if err != nil {
return "", err
}

s = fmt.Sprintf("%dh", durationDays*24)
}

return s, nil
}
62 changes: 36 additions & 26 deletions v3/protos/accesscode/accesscode.pb.go

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

1 change: 1 addition & 0 deletions v3/protos/accesscode/accesscode.proto
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ message OneTimeAccessCode {
string id = 1;
string user = 2;
string redeemed_timestamp = 3;
string max_duration = 4;
}
2 changes: 1 addition & 1 deletion v3/protos/authn/authn.pb.go

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

2 changes: 1 addition & 1 deletion v3/protos/authr/authr.pb.go

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

2 changes: 1 addition & 1 deletion v3/protos/rbac/rbac.pb.go

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

6 changes: 3 additions & 3 deletions v3/protos/setting/setting.pb.go

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

2 changes: 1 addition & 1 deletion v3/protos/user/user.pb.go

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

3 changes: 2 additions & 1 deletion v3/services/accesscodesvc/internal/crd.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ func GenerateAccessCodeCRD() []crder.CRD {
AddVersion("v1", &v1.OneTimeAccessCode{}, func(cv *crder.Version) {
cv.
WithColumn("User", ".spec.user").
WithColumn("Redeemed", ".spec.redeemed_timestamp")
WithColumn("Redeemed", ".spec.redeemed_timestamp").
WithColumn("MaxDuration", ".spec.max_duration")
})
}),
}
Expand Down
2 changes: 2 additions & 0 deletions v3/services/accesscodesvc/internal/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ func (a *GrpcAccessCodeServer) getOtac(id string) (*accessCodeProto.OneTimeAcces
Id: obj.Name,
User: obj.Spec.User,
RedeemedTimestamp: obj.Spec.RedeemedTimestamp,
MaxDuration: obj.Spec.MaxDuration,
}, nil
}

Expand Down Expand Up @@ -108,6 +109,7 @@ func (a *GrpcAccessCodeServer) UpdateOtac(ctx context.Context, otacRequest *acce

otac.Spec.User = otacRequest.GetUser()
otac.Spec.RedeemedTimestamp = otacRequest.GetRedeemedTimestamp()
otac.Spec.MaxDuration = otacRequest.GetMaxDuration()
otac.Labels[util.UserLabel] = otacRequest.GetUser()

_, updateErr := a.hfClientSet.HobbyfarmV1().OneTimeAccessCodes(util.GetReleaseNamespace()).Update(a.ctx, otac, metav1.UpdateOptions{})
Expand Down