Change code generator (#4)

* Change code generator
* Remove gin
This commit is contained in:
Jonas Plum
2022-01-08 00:48:44 +01:00
committed by GitHub
parent b5dd0cfacd
commit 8333ea88a8
148 changed files with 3077 additions and 23976 deletions

345
auth.go
View File

@@ -4,21 +4,20 @@ import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/base64" "encoding/base64"
"encoding/json"
"errors"
"fmt" "fmt"
"log"
"math/rand" "math/rand"
"net/http" "net/http"
"strings" "strings"
"time"
"github.com/coreos/go-oidc/v3/oidc" "github.com/coreos/go-oidc/v3/oidc"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2" "golang.org/x/oauth2"
"github.com/SecurityBrewery/catalyst/database" "github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/hooks" "github.com/SecurityBrewery/catalyst/hooks"
"github.com/SecurityBrewery/catalyst/role" "github.com/SecurityBrewery/catalyst/role"
) )
@@ -59,33 +58,31 @@ func (c *AuthConfig) Load(ctx context.Context) error {
} }
const ( const (
SessionName = "catalyst-session" stateSessionCookie = "state"
stateSession = "state" userSessionCookie = "user"
userSession = "user"
) )
func Authenticate(db *database.Database, config *AuthConfig) gin.HandlerFunc { func Authenticate(db *database.Database, config *AuthConfig) func(next http.Handler) http.Handler {
return func(ctx *gin.Context) { return func(next http.Handler) http.Handler {
iss := config.OIDCIssuer return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
keyHeader := r.Header.Get("PRIVATE-TOKEN")
authHeader := r.Header.Get("User")
keyHeader := ctx.Request.Header.Get("PRIVATE-TOKEN") switch {
if keyHeader != "" { case keyHeader != "":
keyAuth(db, keyHeader)(ctx) keyAuth(db, keyHeader)(next).ServeHTTP(w, r)
return case authHeader != "":
} iss := config.OIDCIssuer
bearerAuth(db, authHeader, iss, config)(next).ServeHTTP(w, r)
authHeader := ctx.Request.Header.Get("User") default:
sessionAuth(db, config)(next).ServeHTTP(w, r)
if authHeader != "" { }
bearerAuth(db, authHeader, iss, config)(ctx) })
return
}
sessionAuth(db, config)(ctx)
} }
} }
func oidcCtx(ctx *gin.Context) (context.Context, context.CancelFunc) { /*
/* func oidcCtx(w http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc) {
if config.TLSCertFile != "" && config.TLSKeyFile != "" { if config.TLSCertFile != "" && config.TLSKeyFile != "" {
cert, err := tls.LoadX509KeyPair(config.TLSCertFile, config.TLSKeyFile) cert, err := tls.LoadX509KeyPair(config.TLSCertFile, config.TLSKeyFile)
if err != nil { if err != nil {
@@ -109,137 +106,145 @@ func oidcCtx(ctx *gin.Context) (context.Context, context.CancelFunc) {
}, },
}), nil }), nil
} }
*/
cctx, cancel := context.WithTimeout(ctx, time.Minute) cctx, cancel := context.WithTimeout(ctx, time.Minute)
return cctx, cancel return cctx, cancel
} }
*/
func bearerAuth(db *database.Database, authHeader string, iss string, config *AuthConfig) func(ctx *gin.Context) { func bearerAuth(db *database.Database, authHeader string, iss string, config *AuthConfig) func(next http.Handler) http.Handler {
return func(ctx *gin.Context) { return func(next http.Handler) http.Handler {
if !strings.HasPrefix(authHeader, "Bearer ") { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "no bearer token"}) if !strings.HasPrefix(authHeader, "Bearer ") {
return api.JSONErrorStatus(w, http.StatusUnauthorized, errors.New("no bearer token"))
} return
}
oidcCtx, cancel := oidcCtx(ctx) // oidcCtx, cancel := oidcCtx(ctx)
defer cancel() // defer cancel()
verifier, err := config.Verifier(oidcCtx) verifier, err := config.Verifier(r.Context())
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "could not verify: " + err.Error()}) api.JSONErrorStatus(w, http.StatusUnauthorized, fmt.Errorf("could not verify: %w", err))
return return
} }
authToken, err := verifier.Verify(oidcCtx, authHeader[7:]) authToken, err := verifier.Verify(r.Context(), authHeader[7:])
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not verify bearer token: %v", err)}) api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not verify bearer token: %w", err))
return return
} }
var claims map[string]interface{} var claims map[string]interface{}
if err := authToken.Claims(&claims); err != nil { if err := authToken.Claims(&claims); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to parse claims: %v", err)}) api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("failed to parse claims: %w", err))
return return
} }
// if claims.Iss != iss { // if claims.Iss != iss {
// ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "wrong issuer"}) // return &api.HTTPError{Status: http.StatusInternalServerError, Internal: "wrong issuer"})
// return // return
// } // }
session := sessions.Default(ctx) b, _ := json.Marshal(claims)
session.Set(userSession, claims) http.SetCookie(w, &http.Cookie{Name: userSessionCookie, Value: base64.StdEncoding.EncodeToString(b)})
if err = session.Save(); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, fmt.Sprintf("could not set session: %v", err))
return
}
if err = setContextClaims(ctx, db, claims, config); err != nil { r, err = setContextClaims(r, db, claims, config)
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not load user: %s", err)}) if err != nil {
return api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not load user: %w", err))
} return
ctx.Next() }
next.ServeHTTP(w, r)
})
} }
} }
func keyAuth(db *database.Database, keyHeader string) func(ctx *gin.Context) { func keyAuth(db *database.Database, keyHeader string) func(next http.Handler) http.Handler {
return func(ctx *gin.Context) { return func(next http.Handler) http.Handler {
h := fmt.Sprintf("%x", sha256.Sum256([]byte(keyHeader))) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := fmt.Sprintf("%x", sha256.Sum256([]byte(keyHeader)))
key, err := db.UserByHash(ctx, h) key, err := db.UserByHash(r.Context(), h)
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not verify private token: %v", err)}) api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not verify private token: %w", err))
return return
} }
setContextUser(ctx, key, db.Hooks) r = setContextUser(r, key, db.Hooks)
ctx.Next() next.ServeHTTP(w, r)
})
} }
} }
func sessionAuth(db *database.Database, config *AuthConfig) func(ctx *gin.Context) { func sessionAuth(db *database.Database, config *AuthConfig) func(next http.Handler) http.Handler {
return func(ctx *gin.Context) { return func(next http.Handler) http.Handler {
session := sessions.Default(ctx) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userCookie, err := r.Cookie(userSessionCookie)
if err != nil {
redirectToLogin(w, r, config.OAuth2)
user := session.Get(userSession) return
if user == nil { }
redirectToLogin(ctx, session, config.OAuth2)
return b, err := base64.StdEncoding.DecodeString(userCookie.Value)
} if err != nil {
api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not decode cookie: %w", err))
return
}
claims, ok := user.(map[string]interface{}) var claims map[string]interface{}
if !ok { if err := json.Unmarshal(b, &claims); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "claims not in session"}) api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("claims not in session"))
return return
} }
if err := setContextClaims(ctx, db, claims, config); err != nil { r, err = setContextClaims(r, db, claims, config)
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not load user: %s", err)}) if err != nil {
return api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not load user: %w", err))
} return
}
ctx.Next() next.ServeHTTP(w, r)
})
} }
} }
func setContextClaims(ctx *gin.Context, db *database.Database, claims map[string]interface{}, config *AuthConfig) error { func setContextClaims(r *http.Request, db *database.Database, claims map[string]interface{}, config *AuthConfig) (*http.Request, error) {
newUser, newSetting, err := mapUserAndSettings(claims, config) newUser, newSetting, err := mapUserAndSettings(claims, config)
if err != nil { if err != nil {
return err return nil, err
} }
if _, ok := busdb.UserFromContext(ctx); !ok { if _, ok := busdb.UserFromContext(r.Context()); !ok {
busdb.SetContext(ctx, &models.UserResponse{ID: "auth", Roles: []string{role.Admin}, Apikey: false, Blocked: false}) r = busdb.SetContext(r, &model.UserResponse{ID: "auth", Roles: []string{role.Admin}, Apikey: false, Blocked: false})
} }
user, err := db.UserGetOrCreate(ctx, newUser) user, err := db.UserGetOrCreate(r.Context(), newUser)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = db.UserDataGetOrCreate(ctx, newUser.ID, newSetting) _, err = db.UserDataGetOrCreate(r.Context(), newUser.ID, newSetting)
if err != nil { if err != nil {
return err return nil, err
} }
setContextUser(ctx, user, db.Hooks) return setContextUser(r, user, db.Hooks), nil
return nil
} }
func setContextUser(ctx *gin.Context, user *models.UserResponse, hooks *hooks.Hooks) { func setContextUser(r *http.Request, user *model.UserResponse, hooks *hooks.Hooks) *http.Request {
groups, err := hooks.GetGroups(ctx, user.ID) groups, err := hooks.GetGroups(r.Context(), user.ID)
if err == nil { if err == nil {
busdb.SetGroupContext(ctx, groups) r = busdb.SetGroupContext(r, groups)
} }
busdb.SetContext(ctx, user) return busdb.SetContext(r, user)
} }
func mapUserAndSettings(claims map[string]interface{}, config *AuthConfig) (*models.UserForm, *models.UserData, error) { func mapUserAndSettings(claims map[string]interface{}, config *AuthConfig) (*model.UserForm, *model.UserData, error) {
// handle Bearer tokens // handle Bearer tokens
// if typ, ok := claims["typ"]; ok && typ == "Bearer" { // if typ, ok := claims["typ"]; ok && typ == "Bearer" {
// return &models.User{ // return &model.User{
// Username: "bot", // Username: "bot",
// Blocked: false, // Blocked: false,
// Email: pointer.String("bot@example.org"), // Email: pointer.String("bot@example.org"),
@@ -262,11 +267,11 @@ func mapUserAndSettings(claims map[string]interface{}, config *AuthConfig) (*mod
name = "" name = ""
} }
return &models.UserForm{ return &model.UserForm{
ID: username, ID: username,
Blocked: config.AuthBlockNew, Blocked: config.AuthBlockNew,
Roles: role.Strings(config.AuthDefaultRoles), Roles: role.Strings(config.AuthDefaultRoles),
}, &models.UserData{ }, &model.UserData{
Email: &email, Email: &email,
Name: &name, Name: &name,
}, nil }, nil
@@ -283,114 +288,110 @@ func getString(m map[string]interface{}, key string) (string, error) {
return "", fmt.Errorf("mapping of %s failed, missing value", key) return "", fmt.Errorf("mapping of %s failed, missing value", key)
} }
func redirectToLogin(ctx *gin.Context, session sessions.Session, oauth2Config *oauth2.Config) { func redirectToLogin(w http.ResponseWriter, r *http.Request, oauth2Config *oauth2.Config) {
state, err := state() state, err := state()
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "generating state failed"}) api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("generating state failed"))
return
}
session.Set(stateSession, state)
err = session.Save()
if err != nil {
log.Println(err)
}
ctx.Redirect(http.StatusFound, oauth2Config.AuthCodeURL(state))
log.Println("abort", ctx.Request.URL.String())
ctx.Abort()
}
func AuthorizeBlockedUser(ctx *gin.Context) {
user, ok := busdb.UserFromContext(ctx)
if !ok {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "no user in context"})
return return
} }
if user.Blocked { http.SetCookie(w, &http.Cookie{Name: stateSessionCookie, Value: state})
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "user is blocked"})
return
}
ctx.Next() http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusFound)
return
} }
func AuthorizeRole(roles []role.Role) gin.HandlerFunc { func AuthorizeBlockedUser() func(http.Handler) http.Handler {
return func(ctx *gin.Context) { return func(next http.Handler) http.Handler {
user, ok := busdb.UserFromContext(ctx) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !ok { user, ok := busdb.UserFromContext(r.Context())
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "no user in context"}) if !ok {
return api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("no user in context"))
} return
}
if !role.UserHasRoles(user, roles) { if user.Blocked {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": fmt.Sprintf("missing role %s has %s", roles, user.Roles)}) api.JSONErrorStatus(w, http.StatusForbidden, errors.New("user is blocked"))
return return
} }
ctx.Next() next.ServeHTTP(w, r)
})
} }
} }
func callback(config *AuthConfig) gin.HandlerFunc { func AuthorizeRole(roles []string) func(http.Handler) http.Handler {
return func(ctx *gin.Context) { return func(next http.Handler) http.Handler {
session := sessions.Default(ctx) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := busdb.UserFromContext(r.Context())
if !ok {
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("no user in context"))
return
}
state := session.Get(stateSession) if !role.UserHasRoles(user, role.FromStrings(roles)) {
if state == "" { api.JSONErrorStatus(w, http.StatusForbidden, fmt.Errorf("missing role %s has %s", roles, user.Roles))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "state missing"}) return
}
next.ServeHTTP(w, r)
})
}
}
func callback(config *AuthConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
stateCookie, err := r.Cookie(stateSessionCookie)
if err != nil || stateCookie.Value == "" {
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("state missing"))
return return
} }
if state != ctx.Query("state") { if stateCookie.Value != r.URL.Query().Get("state") {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "state mismatch"}) api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("state mismatch"))
return return
} }
oauth2Token, err := config.OAuth2.Exchange(ctx, ctx.Query("code")) oauth2Token, err := config.OAuth2.Exchange(r.Context(), r.URL.Query().Get("code"))
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": gin.H{"error": fmt.Sprintf("oauth2 exchange failed: %s", err)}}) api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("oauth2 exchange failed: %w", err))
return return
} }
// Extract the ID Token from OAuth2 token. // Extract the ID Token from OAuth2 token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string) rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok { if !ok {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "missing id token"}) api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("missing id token"))
return return
} }
oidcCtx, cancel := oidcCtx(ctx) // oidcCtx, cancel := oidcCtx(ctx)
defer cancel() // defer cancel()
verifier, err := config.Verifier(oidcCtx) verifier, err := config.Verifier(r.Context())
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "could not verify: " + err.Error()}) api.JSONErrorStatus(w, http.StatusUnauthorized, fmt.Errorf("could not verify: %w", err))
return return
} }
// Parse and verify ID Token payload. // Parse and verify ID Token payload.
idToken, err := verifier.Verify(oidcCtx, rawIDToken) idToken, err := verifier.Verify(r.Context(), rawIDToken)
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "token verification failed: " + err.Error()}) api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("token verification failed: %w", err))
return return
} }
// Extract custom claims // Extract custom claims
var claims map[string]interface{} var claims map[string]interface{}
if err := idToken.Claims(&claims); err != nil { if err := idToken.Claims(&claims); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "claim extraction failed"}) api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("claim extraction failed"))
return return
} }
session.Set(userSession, claims) b, _ := json.Marshal(claims)
err = session.Save() http.SetCookie(w, &http.Cookie{Name: userSessionCookie, Value: base64.StdEncoding.EncodeToString(b)})
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not save session %s", err)})
return
}
ctx.Redirect(http.StatusFound, "/") http.Redirect(w, r, "/", http.StatusFound)
} }
} }

View File

@@ -5,7 +5,6 @@ import (
"bytes" "bytes"
"io" "io"
"io/fs" "io/fs"
"log"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
@@ -13,20 +12,19 @@ import (
"strings" "strings"
"github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/database" "github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/storage" "github.com/SecurityBrewery/catalyst/storage"
) )
func BackupHandler(catalystStorage *storage.Storage, c *database.Config) gin.HandlerFunc { func BackupHandler(catalystStorage *storage.Storage, c *database.Config) http.HandlerFunc {
return func(context *gin.Context) { return func(w http.ResponseWriter, r *http.Request) {
context.Header("Content-Disposition", "attachment; filename=backup.zip") w.Header().Set("Content-Disposition", "attachment; filename=backup.zip")
context.Header("Content-Type", "application/zip") w.Header().Set("Content-Type", "application/zip")
err := Backup(catalystStorage, c, context.Writer) err := Backup(catalystStorage, c, w)
if err != nil { if err != nil {
log.Println(err) api.JSONError(w, err)
context.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
} }
} }
} }

View File

@@ -6,24 +6,24 @@ import (
emitter "github.com/emitter-io/go/v2" emitter "github.com/emitter-io/go/v2"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
const channelJob = "job" const channelJob = "job"
type JobMsg struct { type JobMsg struct {
ID string `json:"id"` ID string `json:"id"`
Automation string `json:"automation"` Automation string `json:"automation"`
Origin *models.Origin `json:"origin"` Origin *model.Origin `json:"origin"`
Message *models.Message `json:"message"` Message *model.Message `json:"message"`
} }
func (b *Bus) PublishJob(id, automation string, payload interface{}, context *models.Context, origin *models.Origin) error { func (b *Bus) PublishJob(id, automation string, payload interface{}, context *model.Context, origin *model.Origin) error {
return b.jsonPublish(&JobMsg{ return b.jsonPublish(&JobMsg{
ID: id, ID: id,
Automation: automation, Automation: automation,
Origin: origin, Origin: origin,
Message: &models.Message{ Message: &model.Message{
Context: context, Context: context,
Payload: payload, Payload: payload,
}, },

View File

@@ -6,7 +6,7 @@ import (
emitter "github.com/emitter-io/go/v2" emitter "github.com/emitter-io/go/v2"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
const channelResult = "result" const channelResult = "result"
@@ -14,10 +14,10 @@ const channelResult = "result"
type ResultMsg struct { type ResultMsg struct {
Automation string `json:"automation"` Automation string `json:"automation"`
Data map[string]interface{} `json:"data,omitempty"` Data map[string]interface{} `json:"data,omitempty"`
Target *models.Origin `json:"target"` Target *model.Origin `json:"target"`
} }
func (b *Bus) PublishResult(automation string, data map[string]interface{}, target *models.Origin) error { func (b *Bus) PublishResult(automation string, data map[string]interface{}, target *model.Origin) error {
return b.jsonPublish(&ResultMsg{Automation: automation, Data: data, Target: target}, channelResult, b.config.resultBusKey) return b.jsonPublish(&ResultMsg{Automation: automation, Data: data, Target: target}, channelResult, b.config.resultBusKey)
} }

View File

@@ -7,7 +7,7 @@ import (
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database" "github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/role" "github.com/SecurityBrewery/catalyst/role"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
@@ -19,9 +19,9 @@ type busService struct {
catalystBus *bus.Bus catalystBus *bus.Bus
} }
func New(apiurl, apikey string, catalystBus *bus.Bus, db *database.Database) error { func New(apiURL, apikey string, catalystBus *bus.Bus, db *database.Database) error {
h := &busService{db: db, apiURL: apiurl, apiKey: apikey, catalystBus: catalystBus} h := &busService{db: db, apiURL: apiURL, apiKey: apikey, catalystBus: catalystBus}
if err := catalystBus.SubscribeRequest(h.logRequest); err != nil { if err := catalystBus.SubscribeRequest(h.logRequest); err != nil {
return err return err
@@ -38,14 +38,14 @@ func New(apiurl, apikey string, catalystBus *bus.Bus, db *database.Database) err
func busContext() context.Context { func busContext() context.Context {
// TODO: change roles? // TODO: change roles?
bot := &models.UserResponse{ID: "bot", Roles: []string{role.Admin}} bot := &model.UserResponse{ID: "bot", Roles: []string{role.Admin}}
return busdb.UserContext(context.Background(), bot) return busdb.UserContext(context.Background(), bot)
} }
func (h *busService) logRequest(msg *bus.RequestMsg) { func (h *busService) logRequest(msg *bus.RequestMsg) {
var logEntries []*models.LogEntry var logEntries []*model.LogEntry
for _, i := range msg.IDs { for _, i := range msg.IDs {
logEntries = append(logEntries, &models.LogEntry{ logEntries = append(logEntries, &model.LogEntry{
Type: bus.ChannelRequest, Type: bus.ChannelRequest,
Reference: i.String(), Reference: i.String(),
Creator: msg.User, Creator: msg.User,

View File

@@ -6,13 +6,13 @@ import (
"log" "log"
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func (h *busService) handleJob(automationMsg *bus.JobMsg) { func (h *busService) handleJob(automationMsg *bus.JobMsg) {
ctx := busContext() ctx := busContext()
job, err := h.db.JobCreate(ctx, automationMsg.ID, &models.JobForm{ job, err := h.db.JobCreate(ctx, automationMsg.ID, &model.JobForm{
Automation: automationMsg.Automation, Automation: automationMsg.Automation,
Payload: automationMsg.Message.Payload, Payload: automationMsg.Message.Payload,
Origin: automationMsg.Origin, Origin: automationMsg.Origin,
@@ -47,7 +47,7 @@ func (h *busService) handleJob(automationMsg *bus.JobMsg) {
return return
} }
if _, err := h.db.JobUpdate(ctx, automationMsg.ID, &models.Job{ if _, err := h.db.JobUpdate(ctx, automationMsg.ID, &model.Job{
Automation: job.Automation, Automation: job.Automation,
Container: &containerID, Container: &containerID,
Origin: job.Origin, Origin: job.Origin,
@@ -85,7 +85,7 @@ func (h *busService) handleJob(automationMsg *bus.JobMsg) {
} }
/* /*
func getAutomation(automationID string, config *Config) (*models.AutomationResponse, error) { func getAutomation(automationID string, config *Config) (*model.AutomationResponse, error) {
req, err := http.NewRequest(http.MethodGet, config.CatalystAPIUrl+"/automations/"+automationID, nil) req, err := http.NewRequest(http.MethodGet, config.CatalystAPIUrl+"/automations/"+automationID, nil)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -104,7 +104,7 @@ func getAutomation(automationID string, config *Config) (*models.AutomationRespo
return nil, err return nil, err
} }
var automation models.AutomationResponse var automation model.AutomationResponse
if err := json.Unmarshal(b, &automation); err != nil { if err := json.Unmarshal(b, &automation); err != nil {
return nil, err return nil, err
} }

View File

@@ -4,7 +4,7 @@ import (
"log" "log"
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func (h *busService) handleResult(resultMsg *bus.ResultMsg) { func (h *busService) handleResult(resultMsg *bus.ResultMsg) {
@@ -22,7 +22,7 @@ func (h *busService) handleResult(resultMsg *bus.ResultMsg) {
log.Println(err) log.Println(err)
} }
case resultMsg.Target.ArtifactOrigin != nil: case resultMsg.Target.ArtifactOrigin != nil:
enrichment := &models.EnrichmentForm{ enrichment := &model.EnrichmentForm{
Data: resultMsg.Data, Data: resultMsg.Data,
Name: resultMsg.Automation, Name: resultMsg.Automation,
} }

View File

@@ -3,18 +3,16 @@ package main
import ( import (
"context" "context"
"log" "log"
"net/http"
"net/http/httputil" "net/http/httputil"
"net/url" "net/url"
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst" "github.com/SecurityBrewery/catalyst"
"github.com/SecurityBrewery/catalyst/cmd" "github.com/SecurityBrewery/catalyst/cmd"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/hooks" "github.com/SecurityBrewery/catalyst/hooks"
"github.com/SecurityBrewery/catalyst/role" "github.com/SecurityBrewery/catalyst/role"
"github.com/SecurityBrewery/catalyst/test" "github.com/SecurityBrewery/catalyst/test"
@@ -36,30 +34,25 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
demoUser := &models.UserResponse{ID: "demo", Roles: []string{role.Admin}} demoUser := &model.UserResponse{ID: "demo", Roles: []string{role.Admin}}
ctx := busdb.UserContext(context.Background(), demoUser) ctx := busdb.UserContext(context.Background(), demoUser)
if err := test.SetupTestData(ctx, theCatalyst.DB); err != nil { if err := test.SetupTestData(ctx, theCatalyst.DB); err != nil {
log.Fatal(err) log.Fatal(err)
} }
// proxy static requests // proxy static requests
theCatalyst.Server.NoRoute( theCatalyst.Server.With(catalyst.Authenticate(theCatalyst.DB, config.Auth), catalyst.AuthorizeBlockedUser()).NotFound(proxy)
sessions.Sessions(catalyst.SessionName, cookie.NewStore(config.Secret)),
catalyst.Authenticate(theCatalyst.DB, config.Auth),
catalyst.AuthorizeBlockedUser,
proxy,
)
if err = theCatalyst.Server.RunWithSigHandler(); err != nil { if err := http.ListenAndServe(":8000", theCatalyst.Server); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }
func proxy(ctx *gin.Context) { func proxy(w http.ResponseWriter, r *http.Request) {
u, _ := url.Parse("http://localhost:8080") u, _ := url.Parse("http://localhost:8080")
proxy := httputil.NewSingleHostReverseProxy(u) proxy := httputil.NewSingleHostReverseProxy(u)
ctx.Request.Host = ctx.Request.URL.Host r.Host = r.URL.Host
proxy.ServeHTTP(ctx.Writer, ctx.Request) proxy.ServeHTTP(w, r)
} }

View File

@@ -2,6 +2,7 @@ package main
import ( import (
"log" "log"
"net/http"
"github.com/SecurityBrewery/catalyst" "github.com/SecurityBrewery/catalyst"
"github.com/SecurityBrewery/catalyst/cmd" "github.com/SecurityBrewery/catalyst/cmd"
@@ -21,7 +22,7 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
if err = theCatalyst.Server.RunWithSigHandler(); err != nil { if err := http.ListenAndServe(":8000", theCatalyst.Server); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }

View File

@@ -11,7 +11,7 @@ import (
"github.com/SecurityBrewery/catalyst" "github.com/SecurityBrewery/catalyst"
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database" "github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/pointer" "github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/role" "github.com/SecurityBrewery/catalyst/role"
"github.com/SecurityBrewery/catalyst/storage" "github.com/SecurityBrewery/catalyst/storage"
@@ -72,10 +72,10 @@ func MapConfig(cli CLI) (*catalyst.Config, error) {
} }
if len(artifactStates) == 0 { if len(artifactStates) == 0 {
artifactStates = []*models.Type{ artifactStates = []*model.Type{
{Icon: "mdi-help-circle-outline", ID: "unknown", Name: "Unknown", Color: pointer.String(models.TypeColorInfo)}, {Icon: "mdi-help-circle-outline", ID: "unknown", Name: "Unknown", Color: pointer.String(model.TypeColorInfo)},
{Icon: "mdi-skull", ID: "malicious", Name: "Malicious", Color: pointer.String(models.TypeColorError)}, {Icon: "mdi-skull", ID: "malicious", Name: "Malicious", Color: pointer.String(model.TypeColorError)},
{Icon: "mdi-check", ID: "clean", Name: "Clean", Color: pointer.String(models.TypeColorSuccess)}, {Icon: "mdi-check", ID: "clean", Name: "Clean", Color: pointer.String(model.TypeColorSuccess)},
} }
} }
@@ -96,21 +96,21 @@ func MapConfig(cli CLI) (*catalyst.Config, error) {
AuthDefaultRoles: roles, AuthDefaultRoles: roles,
}, },
Bus: &bus.Config{Host: cli.EmitterIOHost, Key: cli.EmitterIORKey, APIUrl: cli.CatalystAddress + "/api"}, Bus: &bus.Config{Host: cli.EmitterIOHost, Key: cli.EmitterIORKey, APIUrl: cli.CatalystAddress + "/api"},
UISettings: &models.Settings{ UISettings: &model.Settings{
ArtifactStates: artifactStates, ArtifactStates: artifactStates,
Timeformat: cli.Timeformat, Timeformat: cli.Timeformat,
Version: catalyst.GetVersion(), Version: catalyst.GetVersion(),
Tier: models.SettingsTierCommunity, Tier: model.SettingsTierCommunity,
}, },
InitialAPIKey: cli.InitialAPIKey, InitialAPIKey: cli.InitialAPIKey,
} }
return config, nil return config, nil
} }
func toTypes(params []map[string]string) ([]*models.Type, error) { func toTypes(params []map[string]string) ([]*model.Type, error) {
var types []*models.Type var types []*model.Type
for _, param := range params { for _, param := range params {
t := &models.Type{} t := &model.Type{}
icon, iconOK := param["icon"] icon, iconOK := param["icon"]
if iconOK { if iconOK {

View File

@@ -8,11 +8,11 @@ import (
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*models.Artifact, error) { func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*model.Artifact, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -33,7 +33,7 @@ func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*mo
} }
defer cursor.Close() defer cursor.Close()
var doc models.Artifact var doc model.Artifact
_, err = cursor.ReadDocument(ctx, &doc) _, err = cursor.ReadDocument(ctx, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -42,7 +42,7 @@ func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*mo
return &doc, nil return &doc, nil
} }
func (db *Database) ArtifactUpdate(ctx context.Context, id int64, name string, artifact *models.Artifact) (*models.TicketWithTickets, error) { func (db *Database) ArtifactUpdate(ctx context.Context, id int64, name string, artifact *model.Artifact) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -68,8 +68,8 @@ func (db *Database) ArtifactUpdate(ctx context.Context, id int64, name string, a
}) })
} }
func (db *Database) EnrichArtifact(ctx context.Context, id int64, name string, enrichmentForm *models.EnrichmentForm) (*models.TicketWithTickets, error) { func (db *Database) EnrichArtifact(ctx context.Context, id int64, name string, enrichmentForm *model.EnrichmentForm) (*model.TicketWithTickets, error) {
enrichment := models.Enrichment{time.Now().UTC(), enrichmentForm.Data, enrichmentForm.Name} enrichment := model.Enrichment{time.Now().UTC(), enrichmentForm.Data, enrichmentForm.Name}
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {

View File

@@ -7,11 +7,11 @@ import (
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func toAutomation(doc *models.AutomationForm) interface{} { func toAutomation(doc *model.AutomationForm) interface{} {
return &models.Automation{ return &model.Automation{
Image: doc.Image, Image: doc.Image,
Script: doc.Script, Script: doc.Script,
Schema: doc.Schema, Schema: doc.Schema,
@@ -19,8 +19,8 @@ func toAutomation(doc *models.AutomationForm) interface{} {
} }
} }
func toAutomationResponse(id string, doc models.Automation) *models.AutomationResponse { func toAutomationResponse(id string, doc model.Automation) *model.AutomationResponse {
return &models.AutomationResponse{ return &model.AutomationResponse{
ID: id, ID: id,
Image: doc.Image, Image: doc.Image,
Script: doc.Script, Script: doc.Script,
@@ -29,7 +29,7 @@ func toAutomationResponse(id string, doc models.Automation) *models.AutomationRe
} }
} }
func (db *Database) AutomationCreate(ctx context.Context, automation *models.AutomationForm) (*models.AutomationResponse, error) { func (db *Database) AutomationCreate(ctx context.Context, automation *model.AutomationForm) (*model.AutomationResponse, error) {
if automation == nil { if automation == nil {
return nil, errors.New("requires automation") return nil, errors.New("requires automation")
} }
@@ -37,7 +37,7 @@ func (db *Database) AutomationCreate(ctx context.Context, automation *models.Aut
return nil, errors.New("requires automation ID") return nil, errors.New("requires automation ID")
} }
var doc models.Automation var doc model.Automation
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.automationCollection.CreateDocument(ctx, newctx, automation.ID, toAutomation(automation)) meta, err := db.automationCollection.CreateDocument(ctx, newctx, automation.ID, toAutomation(automation))
@@ -48,8 +48,8 @@ func (db *Database) AutomationCreate(ctx context.Context, automation *models.Aut
return toAutomationResponse(meta.Key, doc), nil return toAutomationResponse(meta.Key, doc), nil
} }
func (db *Database) AutomationGet(ctx context.Context, id string) (*models.AutomationResponse, error) { func (db *Database) AutomationGet(ctx context.Context, id string) (*model.AutomationResponse, error) {
var doc models.Automation var doc model.Automation
meta, err := db.automationCollection.ReadDocument(ctx, id, &doc) meta, err := db.automationCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -58,8 +58,8 @@ func (db *Database) AutomationGet(ctx context.Context, id string) (*models.Autom
return toAutomationResponse(meta.Key, doc), nil return toAutomationResponse(meta.Key, doc), nil
} }
func (db *Database) AutomationUpdate(ctx context.Context, id string, automation *models.AutomationForm) (*models.AutomationResponse, error) { func (db *Database) AutomationUpdate(ctx context.Context, id string, automation *model.AutomationForm) (*model.AutomationResponse, error) {
var doc models.Automation var doc model.Automation
ctx = driver.WithReturnNew(ctx, &doc) ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.automationCollection.ReplaceDocument(ctx, id, toAutomation(automation)) meta, err := db.automationCollection.ReplaceDocument(ctx, id, toAutomation(automation))
@@ -75,16 +75,16 @@ func (db *Database) AutomationDelete(ctx context.Context, id string) error {
return err return err
} }
func (db *Database) AutomationList(ctx context.Context) ([]*models.AutomationResponse, error) { func (db *Database) AutomationList(ctx context.Context) ([]*model.AutomationResponse, error) {
query := "FOR d IN @@collection SORT d._key ASC RETURN UNSET(d, 'script')" query := "FOR d IN @@collection SORT d._key ASC RETURN UNSET(d, 'script')"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": AutomationCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": AutomationCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.AutomationResponse var docs []*model.AutomationResponse
for { for {
var doc models.Automation var doc model.Automation
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break

View File

@@ -2,11 +2,13 @@ package busdb
import ( import (
"context" "context"
"errors"
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/generated/model"
) )
// BusDatabase // BusDatabase
@@ -41,14 +43,14 @@ type Operation struct {
var CreateOperation = &Operation{Type: bus.DatabaseEntryCreated} var CreateOperation = &Operation{Type: bus.DatabaseEntryCreated}
var ReadOperation = &Operation{Type: bus.DatabaseEntryRead} var ReadOperation = &Operation{Type: bus.DatabaseEntryRead}
func (db BusDatabase) Query(ctx context.Context, query string, vars map[string]interface{}, operation *Operation) (driver.Cursor, *models.LogEntry, error) { func (db BusDatabase) Query(ctx context.Context, query string, vars map[string]interface{}, operation *Operation) (cur driver.Cursor, logs *model.LogEntry, err error) {
cur, err := db.internal.Query(ctx, query, vars) defer func() { err = toHTTPErr(err) }()
cur, err = db.internal.Query(ctx, query, vars)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
var logs *models.LogEntry
switch { switch {
case operation.Type == bus.DatabaseEntryCreated, operation.Type == bus.DatabaseEntryUpdated: case operation.Type == bus.DatabaseEntryCreated, operation.Type == bus.DatabaseEntryUpdated:
if err := db.bus.PublishDatabaseUpdate(operation.Ids, operation.Type); err != nil { if err := db.bus.PublishDatabaseUpdate(operation.Ids, operation.Type); err != nil {
@@ -59,11 +61,15 @@ func (db BusDatabase) Query(ctx context.Context, query string, vars map[string]i
return cur, logs, err return cur, logs, err
} }
func (db BusDatabase) Remove(ctx context.Context) error { func (db BusDatabase) Remove(ctx context.Context) (err error) {
defer func() { err = toHTTPErr(err) }()
return db.internal.Remove(ctx) return db.internal.Remove(ctx)
} }
func (db BusDatabase) Collection(ctx context.Context, name string) (driver.Collection, error) { func (db BusDatabase) Collection(ctx context.Context, name string) (col driver.Collection, err error) {
defer func() { err = toHTTPErr(err) }()
return db.internal.Collection(ctx, name) return db.internal.Collection(ctx, name)
} }
@@ -76,8 +82,10 @@ func NewCollection(internal driver.Collection, db *BusDatabase) *Collection {
return &Collection{internal: internal, db: db} return &Collection{internal: internal, db: db}
} }
func (c Collection) CreateDocument(ctx, newctx context.Context, key string, document interface{}) (driver.DocumentMeta, error) { func (c Collection) CreateDocument(ctx, newctx context.Context, key string, document interface{}) (meta driver.DocumentMeta, err error) {
meta, err := c.internal.CreateDocument(newctx, &Keyed{Key: key, Doc: document}) defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.CreateDocument(newctx, &Keyed{Key: key, Doc: document})
if err != nil { if err != nil {
return meta, err return meta, err
} }
@@ -89,8 +97,10 @@ func (c Collection) CreateDocument(ctx, newctx context.Context, key string, docu
return meta, nil return meta, nil
} }
func (c Collection) CreateEdge(ctx, newctx context.Context, edge *driver.EdgeDocument) (driver.DocumentMeta, error) { func (c Collection) CreateEdge(ctx, newctx context.Context, edge *driver.EdgeDocument) (meta driver.DocumentMeta, err error) {
meta, err := c.internal.CreateDocument(newctx, edge) defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.CreateDocument(newctx, edge)
if err != nil { if err != nil {
return meta, err return meta, err
} }
@@ -102,7 +112,9 @@ func (c Collection) CreateEdge(ctx, newctx context.Context, edge *driver.EdgeDoc
return meta, nil return meta, nil
} }
func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocument) (driver.DocumentMetaSlice, error) { func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocument) (meta driver.DocumentMetaSlice, err error) {
defer func() { err = toHTTPErr(err) }()
metas, errs, err := c.internal.CreateDocuments(ctx, edges) metas, errs, err := c.internal.CreateDocuments(ctx, edges)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -124,16 +136,24 @@ func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocumen
return metas, nil return metas, nil
} }
func (c Collection) DocumentExists(ctx context.Context, id string) (bool, error) { func (c Collection) DocumentExists(ctx context.Context, id string) (exists bool, err error) {
defer func() { err = toHTTPErr(err) }()
return c.internal.DocumentExists(ctx, id) return c.internal.DocumentExists(ctx, id)
} }
func (c Collection) ReadDocument(ctx context.Context, key string, result interface{}) (driver.DocumentMeta, error) { func (c Collection) ReadDocument(ctx context.Context, key string, result interface{}) (meta driver.DocumentMeta, err error) {
return c.internal.ReadDocument(ctx, key, result) defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.ReadDocument(ctx, key, result)
return
} }
func (c Collection) UpdateDocument(ctx context.Context, key string, update interface{}) (driver.DocumentMeta, error) { func (c Collection) UpdateDocument(ctx context.Context, key string, update interface{}) (meta driver.DocumentMeta, err error) {
meta, err := c.internal.UpdateDocument(ctx, key, update) defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.UpdateDocument(ctx, key, update)
if err != nil { if err != nil {
return meta, err return meta, err
} }
@@ -141,8 +161,10 @@ func (c Collection) UpdateDocument(ctx context.Context, key string, update inter
return meta, c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryUpdated) return meta, c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryUpdated)
} }
func (c Collection) ReplaceDocument(ctx context.Context, key string, document interface{}) (driver.DocumentMeta, error) { func (c Collection) ReplaceDocument(ctx context.Context, key string, document interface{}) (meta driver.DocumentMeta, err error) {
meta, err := c.internal.ReplaceDocument(ctx, key, document) defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.ReplaceDocument(ctx, key, document)
if err != nil { if err != nil {
return meta, err return meta, err
} }
@@ -150,10 +172,24 @@ func (c Collection) ReplaceDocument(ctx context.Context, key string, document in
return meta, c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryUpdated) return meta, c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryUpdated)
} }
func (c Collection) RemoveDocument(ctx context.Context, formatInt string) (driver.DocumentMeta, error) { func (c Collection) RemoveDocument(ctx context.Context, formatInt string) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
return c.internal.RemoveDocument(ctx, formatInt) return c.internal.RemoveDocument(ctx, formatInt)
} }
func (c Collection) Truncate(ctx context.Context) error { func (c Collection) Truncate(ctx context.Context) (err error) {
defer func() { err = toHTTPErr(err) }()
return c.internal.Truncate(ctx) return c.internal.Truncate(ctx)
} }
func toHTTPErr(err error) error {
if err != nil {
ae := driver.ArangoError{}
if errors.As(err, &ae) {
return &api.HTTPError{Status: ae.Code, Internal: err}
}
}
return nil
}

View File

@@ -2,10 +2,9 @@ package busdb
import ( import (
"context" "context"
"net/http"
"github.com/gin-gonic/gin" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/role" "github.com/SecurityBrewery/catalyst/role"
) )
@@ -14,21 +13,22 @@ const (
groupContextKey = "groups" groupContextKey = "groups"
) )
func SetContext(ctx *gin.Context, user *models.UserResponse) { func SetContext(r *http.Request, user *model.UserResponse) *http.Request {
user.Roles = role.Strings(role.Explodes(user.Roles)) user.Roles = role.Strings(role.Explodes(user.Roles))
ctx.Set(userContextKey, user)
return r.WithContext(context.WithValue(r.Context(), userContextKey, user))
} }
func SetGroupContext(ctx *gin.Context, groups []string) { func SetGroupContext(r *http.Request, groups []string) *http.Request {
ctx.Set(groupContextKey, groups) return r.WithContext(context.WithValue(r.Context(), groupContextKey, groups))
} }
func UserContext(ctx context.Context, user *models.UserResponse) context.Context { func UserContext(ctx context.Context, user *model.UserResponse) context.Context {
user.Roles = role.Strings(role.Explodes(user.Roles)) user.Roles = role.Strings(role.Explodes(user.Roles))
return context.WithValue(ctx, userContextKey, user) return context.WithValue(ctx, userContextKey, user)
} }
func UserFromContext(ctx context.Context) (*models.UserResponse, bool) { func UserFromContext(ctx context.Context) (*model.UserResponse, bool) {
u, ok := ctx.Value(userContextKey).(*models.UserResponse) u, ok := ctx.Value(userContextKey).(*model.UserResponse)
return u, ok return u, ok
} }

View File

@@ -3,24 +3,24 @@ package busdb
import ( import (
"context" "context"
"errors" "errors"
"github.com/SecurityBrewery/catalyst/bus"
"strings" "strings"
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
const LogCollectionName = "logs" const LogCollectionName = "logs"
func (db *BusDatabase) LogCreate(ctx context.Context, logType, reference, message string) (*models.LogEntry, error) { func (db *BusDatabase) LogCreate(ctx context.Context, logType, reference, message string) (*model.LogEntry, error) {
user, ok := UserFromContext(ctx) user, ok := UserFromContext(ctx)
if !ok { if !ok {
return nil, errors.New("no user in context") return nil, errors.New("no user in context")
} }
logentry := &models.LogEntry{ logentry := &model.LogEntry{
Type: logType, Type: logType,
Reference: reference, Reference: reference,
Created: time.Now().UTC(), Created: time.Now().UTC(),
@@ -28,7 +28,7 @@ func (db *BusDatabase) LogCreate(ctx context.Context, logType, reference, messag
Message: message, Message: message,
} }
doc := models.LogEntry{} doc := model.LogEntry{}
_, err := db.logCollection.CreateDocument(driver.WithReturnNew(ctx, &doc), logentry) _, err := db.logCollection.CreateDocument(driver.WithReturnNew(ctx, &doc), logentry)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -37,7 +37,7 @@ func (db *BusDatabase) LogCreate(ctx context.Context, logType, reference, messag
return &doc, nil return &doc, nil
} }
func (db *BusDatabase) LogBatchCreate(ctx context.Context, logentries []*models.LogEntry) error { func (db *BusDatabase) LogBatchCreate(ctx context.Context, logentries []*model.LogEntry) error {
var ids []driver.DocumentID var ids []driver.DocumentID
for _, entry := range logentries { for _, entry := range logentries {
if strings.HasPrefix(entry.Reference, "tickets/") { if strings.HasPrefix(entry.Reference, "tickets/") {
@@ -60,7 +60,7 @@ func (db *BusDatabase) LogBatchCreate(ctx context.Context, logentries []*models.
return nil return nil
} }
func (db *BusDatabase) LogList(ctx context.Context, reference string) ([]*models.LogEntry, error) { func (db *BusDatabase) LogList(ctx context.Context, reference string) ([]*model.LogEntry, error) {
query := "FOR d IN @@collection FILTER d.reference == @reference SORT d.created DESC RETURN d" query := "FOR d IN @@collection FILTER d.reference == @reference SORT d.created DESC RETURN d"
cursor, err := db.internal.Query(ctx, query, map[string]interface{}{ cursor, err := db.internal.Query(ctx, query, map[string]interface{}{
"@collection": LogCollectionName, "@collection": LogCollectionName,
@@ -70,9 +70,9 @@ func (db *BusDatabase) LogList(ctx context.Context, reference string) ([]*models
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.LogEntry var docs []*model.LogEntry
for { for {
var doc models.LogEntry var doc model.LogEntry
_, err := cursor.ReadDocument(ctx, &doc) _, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break

View File

@@ -14,11 +14,11 @@ import (
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/caql" "github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func toJob(doc *models.JobForm) *models.Job { func toJob(doc *model.JobForm) *model.Job {
return &models.Job{ return &model.Job{
Automation: doc.Automation, Automation: doc.Automation,
Payload: doc.Payload, Payload: doc.Payload,
Origin: doc.Origin, Origin: doc.Origin,
@@ -27,7 +27,7 @@ func toJob(doc *models.JobForm) *models.Job {
} }
} }
func (db *Database) toJobResponse(ctx context.Context, key string, doc *models.Job, update bool) (*models.JobResponse, error) { func (db *Database) toJobResponse(ctx context.Context, key string, doc *model.Job, update bool) (*model.JobResponse, error) {
cli, err := client.NewClientWithOpts(client.FromEnv) cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -52,7 +52,7 @@ func (db *Database) toJobResponse(ctx context.Context, key string, doc *models.J
} }
} }
return &models.JobResponse{ return &model.JobResponse{
Automation: doc.Automation, Automation: doc.Automation,
ID: key, ID: key,
Log: doc.Log, Log: doc.Log,
@@ -64,19 +64,19 @@ func (db *Database) toJobResponse(ctx context.Context, key string, doc *models.J
}, nil }, nil
} }
func (db *Database) JobCreate(ctx context.Context, id string, job *models.JobForm) (*models.JobResponse, error) { func (db *Database) JobCreate(ctx context.Context, id string, job *model.JobForm) (*model.JobResponse, error) {
if job == nil { if job == nil {
return nil, errors.New("requires job") return nil, errors.New("requires job")
} }
var doc models.Job var doc model.Job
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
/* Start validation */ /* Start validation */
j := toJob(job) j := toJob(job)
b, _ := json.Marshal(j) b, _ := json.Marshal(j)
r, err := models.JobSchema.Validate(gojsonschema.NewBytesLoader(b)) r, err := model.JobSchema.Validate(gojsonschema.NewBytesLoader(b))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -98,8 +98,8 @@ func (db *Database) JobCreate(ctx context.Context, id string, job *models.JobFor
return db.toJobResponse(ctx, meta.Key, &doc, true) return db.toJobResponse(ctx, meta.Key, &doc, true)
} }
func (db *Database) JobGet(ctx context.Context, id string) (*models.JobResponse, error) { func (db *Database) JobGet(ctx context.Context, id string) (*model.JobResponse, error) {
var doc models.Job var doc model.Job
meta, err := db.jobCollection.ReadDocument(ctx, id, &doc) meta, err := db.jobCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -108,14 +108,14 @@ func (db *Database) JobGet(ctx context.Context, id string) (*models.JobResponse,
return db.toJobResponse(ctx, meta.Key, &doc, true) return db.toJobResponse(ctx, meta.Key, &doc, true)
} }
func (db *Database) JobUpdate(ctx context.Context, id string, job *models.Job) (*models.JobResponse, error) { func (db *Database) JobUpdate(ctx context.Context, id string, job *model.Job) (*model.JobResponse, error) {
var doc models.Job var doc model.Job
ctx = driver.WithReturnNew(ctx, &doc) ctx = driver.WithReturnNew(ctx, &doc)
/* Start validation */ /* Start validation */
b, _ := json.Marshal(job) b, _ := json.Marshal(job)
r, err := models.JobSchema.Validate(gojsonschema.NewBytesLoader(b)) r, err := model.JobSchema.Validate(gojsonschema.NewBytesLoader(b))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -184,16 +184,16 @@ func (db *Database) JobDelete(ctx context.Context, id string) error {
return err return err
} }
func (db *Database) JobList(ctx context.Context) ([]*models.JobResponse, error) { func (db *Database) JobList(ctx context.Context) ([]*model.JobResponse, error) {
query := "FOR d IN @@collection RETURN d" query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": JobCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": JobCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.JobResponse var docs []*model.JobResponse
for { for {
var doc models.Job var doc model.Job
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break
@@ -212,7 +212,7 @@ func (db *Database) JobList(ctx context.Context) ([]*models.JobResponse, error)
return docs, err return docs, err
} }
func publishJobMapping(id, automation string, contextStructs *models.Context, origin *models.Origin, payloadMapping map[string]string, db *Database) error { func publishJobMapping(id, automation string, contextStructs *model.Context, origin *model.Origin, payloadMapping map[string]string, db *Database) error {
msg, err := generatePayload(payloadMapping, contextStructs) msg, err := generatePayload(payloadMapping, contextStructs)
if err != nil { if err != nil {
return fmt.Errorf("message generation failed: %w", err) return fmt.Errorf("message generation failed: %w", err)
@@ -221,11 +221,11 @@ func publishJobMapping(id, automation string, contextStructs *models.Context, or
return publishJob(id, automation, contextStructs, origin, msg, db) return publishJob(id, automation, contextStructs, origin, msg, db)
} }
func publishJob(id, automation string, contextStructs *models.Context, origin *models.Origin, payload map[string]interface{}, db *Database) error { func publishJob(id, automation string, contextStructs *model.Context, origin *model.Origin, payload map[string]interface{}, db *Database) error {
return db.bus.PublishJob(id, automation, payload, contextStructs, origin) return db.bus.PublishJob(id, automation, payload, contextStructs, origin)
} }
func generatePayload(msgMapping map[string]string, contextStructs *models.Context) (map[string]interface{}, error) { func generatePayload(msgMapping map[string]string, contextStructs *model.Context) (map[string]interface{}, error) {
contextJson, err := json.Marshal(contextStructs) contextJson, err := json.Marshal(contextStructs)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@@ -7,7 +7,7 @@ import (
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/pointer" "github.com/SecurityBrewery/catalyst/pointer"
) )
@@ -32,23 +32,23 @@ func generateMigrations() ([]Migration, error) {
&createGraph{ID: "create-ticket-graph", Name: "Graph", EdgeDefinitions: []driver.EdgeDefinition{{Collection: "related", From: []string{"tickets"}, To: []string{"tickets"}}}}, &createGraph{ID: "create-ticket-graph", Name: "Graph", EdgeDefinitions: []driver.EdgeDefinition{{Collection: "related", From: []string{"tickets"}, To: []string{"tickets"}}}},
&createDocument{ID: "create-template-default", Collection: "templates", Document: &busdb.Keyed{Key: "default", Doc: models.TicketTemplate{Schema: DefaultTemplateSchema, Name: "Default"}}}, &createDocument{ID: "create-template-default", Collection: "templates", Document: &busdb.Keyed{Key: "default", Doc: model.TicketTemplate{Schema: DefaultTemplateSchema, Name: "Default"}}},
&createDocument{ID: "create-automation-vt.hash", Collection: "automations", Document: &busdb.Keyed{Key: "vt.hash", Doc: models.Automation{Image: "docker.io/python:3", Script: VTHashAutomation}}}, &createDocument{ID: "create-automation-vt.hash", Collection: "automations", Document: &busdb.Keyed{Key: "vt.hash", Doc: model.Automation{Image: "docker.io/python:3", Script: VTHashAutomation}}},
&createDocument{ID: "create-automation-comment", Collection: "automations", Document: &busdb.Keyed{Key: "comment", Doc: models.Automation{Image: "docker.io/python:3", Script: CommentAutomation}}}, &createDocument{ID: "create-automation-comment", Collection: "automations", Document: &busdb.Keyed{Key: "comment", Doc: model.Automation{Image: "docker.io/python:3", Script: CommentAutomation}}},
&createDocument{ID: "create-automation-thehive", Collection: "automations", Document: &busdb.Keyed{Key: "thehive", Doc: models.Automation{Image: "docker.io/python:3", Script: TheHiveAutomation}}}, &createDocument{ID: "create-automation-thehive", Collection: "automations", Document: &busdb.Keyed{Key: "thehive", Doc: model.Automation{Image: "docker.io/python:3", Script: TheHiveAutomation}}},
&createDocument{ID: "create-automation-hash.sha1", Collection: "automations", Document: &busdb.Keyed{Key: "hash.sha1", Doc: models.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation}}}, &createDocument{ID: "create-automation-hash.sha1", Collection: "automations", Document: &busdb.Keyed{Key: "hash.sha1", Doc: model.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation}}},
&createDocument{ID: "create-playbook-malware", Collection: "playbooks", Document: &busdb.Keyed{Key: "malware", Doc: models.PlaybookTemplate{Name: "Malware", Yaml: MalwarePlaybook}}}, &createDocument{ID: "create-playbook-malware", Collection: "playbooks", Document: &busdb.Keyed{Key: "malware", Doc: model.PlaybookTemplate{Name: "Malware", Yaml: MalwarePlaybook}}},
&createDocument{ID: "create-playbook-phishing", Collection: "playbooks", Document: &busdb.Keyed{Key: "phishing", Doc: models.PlaybookTemplate{Name: "Phishing", Yaml: PhishingPlaybook}}}, &createDocument{ID: "create-playbook-phishing", Collection: "playbooks", Document: &busdb.Keyed{Key: "phishing", Doc: model.PlaybookTemplate{Name: "Phishing", Yaml: PhishingPlaybook}}},
&createDocument{ID: "create-tickettype-alert", Collection: "tickettypes", Document: &busdb.Keyed{Key: "alert", Doc: models.TicketType{Name: "Alerts", Icon: "mdi-alert", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}}, &createDocument{ID: "create-tickettype-alert", Collection: "tickettypes", Document: &busdb.Keyed{Key: "alert", Doc: model.TicketType{Name: "Alerts", Icon: "mdi-alert", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-incident", Collection: "tickettypes", Document: &busdb.Keyed{Key: "incident", Doc: models.TicketType{Name: "Incidents", Icon: "mdi-radioactive", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}}, &createDocument{ID: "create-tickettype-incident", Collection: "tickettypes", Document: &busdb.Keyed{Key: "incident", Doc: model.TicketType{Name: "Incidents", Icon: "mdi-radioactive", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-investigation", Collection: "tickettypes", Document: &busdb.Keyed{Key: "investigation", Doc: models.TicketType{Name: "Forensic Investigations", Icon: "mdi-fingerprint", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}}, &createDocument{ID: "create-tickettype-investigation", Collection: "tickettypes", Document: &busdb.Keyed{Key: "investigation", Doc: model.TicketType{Name: "Forensic Investigations", Icon: "mdi-fingerprint", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-hunt", Collection: "tickettypes", Document: &busdb.Keyed{Key: "hunt", Doc: models.TicketType{Name: "Threat Hunting", Icon: "mdi-target", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}}, &createDocument{ID: "create-tickettype-hunt", Collection: "tickettypes", Document: &busdb.Keyed{Key: "hunt", Doc: model.TicketType{Name: "Threat Hunting", Icon: "mdi-target", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&updateSchema{ID: "update-automation-collection-1", Name: "automations", DataType: "automation", Schema: `{"properties":{"image":{"type":"string"},"script":{"type":"string"}},"required":["image","script"],"type":"object"}`}, &updateSchema{ID: "update-automation-collection-1", Name: "automations", DataType: "automation", Schema: `{"properties":{"image":{"type":"string"},"script":{"type":"string"}},"required":["image","script"],"type":"object"}`},
&updateDocument{ID: "update-automation-vt.hash-1", Collection: "automations", Key: "vt.hash", Document: models.Automation{Image: "docker.io/python:3", Script: VTHashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}}, &updateDocument{ID: "update-automation-vt.hash-1", Collection: "automations", Key: "vt.hash", Document: model.Automation{Image: "docker.io/python:3", Script: VTHashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}},
&updateDocument{ID: "update-automation-comment-1", Collection: "automations", Key: "comment", Document: models.Automation{Image: "docker.io/python:3", Script: CommentAutomation, Type: []string{"playbook"}}}, &updateDocument{ID: "update-automation-comment-1", Collection: "automations", Key: "comment", Document: model.Automation{Image: "docker.io/python:3", Script: CommentAutomation, Type: []string{"playbook"}}},
&updateDocument{ID: "update-automation-thehive-1", Collection: "automations", Key: "thehive", Document: models.Automation{Image: "docker.io/python:3", Script: TheHiveAutomation, Schema: pointer.String(`{"title":"TheHive credentials","type":"object","properties":{"thehiveurl":{"type":"string","title":"TheHive URL (e.g. 'https://thehive.example.org')"},"thehivekey":{"type":"string","title":"TheHive API Key"},"skip_files":{"type":"boolean", "default": true, "title":"Skip Files (much faster)"},"keep_ids":{"type":"boolean", "default": true, "title":"Keep IDs and overwrite existing IDs"}},"required":["thehiveurl", "thehivekey", "skip_files", "keep_ids"]}`), Type: []string{"global"}}}, &updateDocument{ID: "update-automation-thehive-1", Collection: "automations", Key: "thehive", Document: model.Automation{Image: "docker.io/python:3", Script: TheHiveAutomation, Schema: pointer.String(`{"title":"TheHive credentials","type":"object","properties":{"thehiveurl":{"type":"string","title":"TheHive URL (e.g. 'https://thehive.example.org')"},"thehivekey":{"type":"string","title":"TheHive API Key"},"skip_files":{"type":"boolean", "default": true, "title":"Skip Files (much faster)"},"keep_ids":{"type":"boolean", "default": true, "title":"Keep IDs and overwrite existing IDs"}},"required":["thehiveurl", "thehivekey", "skip_files", "keep_ids"]}`), Type: []string{"global"}}},
&updateDocument{ID: "update-automation-hash.sha1-1", Collection: "automations", Key: "hash.sha1", Document: models.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}}, &updateDocument{ID: "update-automation-hash.sha1-1", Collection: "automations", Key: "hash.sha1", Document: model.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}},
&createCollection{ID: "create-job-collection", Name: "jobs", DataType: "job", Schema: `{"properties":{"automation":{"type":"string"},"log":{"type":"string"},"payload":{},"origin":{"properties":{"artifact_origin":{"properties":{"artifact":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["artifact","ticket_id"],"type":"object"},"task_origin":{"properties":{"playbook_id":{"type":"string"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["playbook_id","task_id","ticket_id"],"type":"object"}},"type":"object"},"output":{"properties":{},"type":"object"},"running":{"type":"boolean"},"status":{"type":"string"}},"required":["automation","running","status"],"type":"object"}`}, &createCollection{ID: "create-job-collection", Name: "jobs", DataType: "job", Schema: `{"properties":{"automation":{"type":"string"},"log":{"type":"string"},"payload":{},"origin":{"properties":{"artifact_origin":{"properties":{"artifact":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["artifact","ticket_id"],"type":"object"},"task_origin":{"properties":{"playbook_id":{"type":"string"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["playbook_id","task_id","ticket_id"],"type":"object"}},"type":"object"},"output":{"properties":{},"type":"object"},"running":{"type":"boolean"},"status":{"type":"string"}},"required":["automation","running","status"],"type":"object"}`},
}, nil }, nil

View File

@@ -10,7 +10,7 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
@@ -29,8 +29,8 @@ type TaskYAML struct {
Join bool `yaml:"join"` Join bool `yaml:"join"`
} }
func toPlaybooks(docs []*models.PlaybookTemplateForm) (map[string]*models.Playbook, error) { func toPlaybooks(docs []*model.PlaybookTemplateForm) (map[string]*model.Playbook, error) {
playbooks := map[string]*models.Playbook{} playbooks := map[string]*model.Playbook{}
for _, doc := range docs { for _, doc := range docs {
playbook, err := toPlaybook(doc) playbook, err := toPlaybook(doc)
if err != nil { if err != nil {
@@ -45,15 +45,15 @@ func toPlaybooks(docs []*models.PlaybookTemplateForm) (map[string]*models.Playbo
return playbooks, nil return playbooks, nil
} }
func toPlaybook(doc *models.PlaybookTemplateForm) (*models.Playbook, error) { func toPlaybook(doc *model.PlaybookTemplateForm) (*model.Playbook, error) {
ticketPlaybook := &models.Playbook{} ticketPlaybook := &model.Playbook{}
err := yaml.Unmarshal([]byte(doc.Yaml), ticketPlaybook) err := yaml.Unmarshal([]byte(doc.Yaml), ticketPlaybook)
if err != nil { if err != nil {
return nil, err return nil, err
} }
for idx, task := range ticketPlaybook.Tasks { for idx, task := range ticketPlaybook.Tasks {
if task.Schema != nil { if task.Schema != nil {
task.Schema = dyno.ConvertMapI2MapS(task.Schema.(map[string]interface{})) task.Schema = dyno.ConvertMapI2MapS(task.Schema).(map[string]interface{})
} }
task.Created = time.Now().UTC() task.Created = time.Now().UTC()
ticketPlaybook.Tasks[idx] = task ticketPlaybook.Tasks[idx] = task
@@ -61,11 +61,11 @@ func toPlaybook(doc *models.PlaybookTemplateForm) (*models.Playbook, error) {
return ticketPlaybook, nil return ticketPlaybook, nil
} }
func toPlaybookTemplateResponse(key string, doc *models.PlaybookTemplate) *models.PlaybookTemplateResponse { func toPlaybookTemplateResponse(key string, doc *model.PlaybookTemplate) *model.PlaybookTemplateResponse {
return &models.PlaybookTemplateResponse{ID: key, Name: doc.Name, Yaml: doc.Yaml} return &model.PlaybookTemplateResponse{ID: key, Name: doc.Name, Yaml: doc.Yaml}
} }
func (db *Database) PlaybookCreate(ctx context.Context, playbook *models.PlaybookTemplateForm) (*models.PlaybookTemplateResponse, error) { func (db *Database) PlaybookCreate(ctx context.Context, playbook *model.PlaybookTemplateForm) (*model.PlaybookTemplateResponse, error) {
if playbook == nil { if playbook == nil {
return nil, errors.New("requires playbook") return nil, errors.New("requires playbook")
} }
@@ -79,9 +79,9 @@ func (db *Database) PlaybookCreate(ctx context.Context, playbook *models.Playboo
if playbookYAML.Name == "" { if playbookYAML.Name == "" {
return nil, errors.New("requires template name") return nil, errors.New("requires template name")
} }
p := models.PlaybookTemplate{Name: playbookYAML.Name, Yaml: playbook.Yaml} p := model.PlaybookTemplate{Name: playbookYAML.Name, Yaml: playbook.Yaml}
var doc models.PlaybookTemplate var doc model.PlaybookTemplate
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.playbookCollection.CreateDocument(ctx, newctx, strcase.ToKebab(playbookYAML.Name), p) meta, err := db.playbookCollection.CreateDocument(ctx, newctx, strcase.ToKebab(playbookYAML.Name), p)
@@ -92,8 +92,8 @@ func (db *Database) PlaybookCreate(ctx context.Context, playbook *models.Playboo
return toPlaybookTemplateResponse(meta.Key, &doc), nil return toPlaybookTemplateResponse(meta.Key, &doc), nil
} }
func (db *Database) PlaybookGet(ctx context.Context, id string) (*models.PlaybookTemplateResponse, error) { func (db *Database) PlaybookGet(ctx context.Context, id string) (*model.PlaybookTemplateResponse, error) {
doc := models.PlaybookTemplate{} doc := model.PlaybookTemplate{}
meta, err := db.playbookCollection.ReadDocument(ctx, id, &doc) meta, err := db.playbookCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -107,7 +107,7 @@ func (db *Database) PlaybookDelete(ctx context.Context, id string) error {
return err return err
} }
func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *models.PlaybookTemplateForm) (*models.PlaybookTemplateResponse, error) { func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *model.PlaybookTemplateForm) (*model.PlaybookTemplateResponse, error) {
var pb PlaybookYAML var pb PlaybookYAML
err := yaml.Unmarshal([]byte(playbook.Yaml), &pb) err := yaml.Unmarshal([]byte(playbook.Yaml), &pb)
if err != nil { if err != nil {
@@ -118,10 +118,10 @@ func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *mod
return nil, errors.New("requires template name") return nil, errors.New("requires template name")
} }
var doc models.PlaybookTemplate var doc model.PlaybookTemplate
ctx = driver.WithReturnNew(ctx, &doc) ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.playbookCollection.ReplaceDocument(ctx, id, models.PlaybookTemplate{Name: pb.Name, Yaml: playbook.Yaml}) meta, err := db.playbookCollection.ReplaceDocument(ctx, id, model.PlaybookTemplate{Name: pb.Name, Yaml: playbook.Yaml})
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -129,16 +129,16 @@ func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *mod
return toPlaybookTemplateResponse(meta.Key, &doc), nil return toPlaybookTemplateResponse(meta.Key, &doc), nil
} }
func (db *Database) PlaybookList(ctx context.Context) ([]*models.PlaybookTemplateResponse, error) { func (db *Database) PlaybookList(ctx context.Context) ([]*model.PlaybookTemplateResponse, error) {
query := "FOR d IN @@collection RETURN d" query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": PlaybookCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": PlaybookCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.PlaybookTemplateResponse var docs []*model.PlaybookTemplateResponse
for { for {
var doc models.PlaybookTemplate var doc model.PlaybookTemplate
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break

View File

@@ -8,10 +8,10 @@ import (
"github.com/SecurityBrewery/catalyst/caql" "github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/dag" "github.com/SecurityBrewery/catalyst/dag"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func playbookGraph(playbook *models.Playbook) (*dag.Graph, error) { func playbookGraph(playbook *model.Playbook) (*dag.Graph, error) {
d := dag.NewGraph() d := dag.NewGraph()
var taskIDs []string var taskIDs []string
@@ -36,13 +36,13 @@ func playbookGraph(playbook *models.Playbook) (*dag.Graph, error) {
return d, nil return d, nil
} }
func toTaskResponse(playbook *models.Playbook, taskID string, order int, graph *dag.Graph) (*models.TaskResponse, error) { func toTaskResponse(playbook *model.Playbook, taskID string, order int, graph *dag.Graph) (*model.TaskResponse, error) {
task, ok := playbook.Tasks[taskID] task, ok := playbook.Tasks[taskID]
if !ok { if !ok {
return nil, fmt.Errorf("task %s not found", taskID) return nil, fmt.Errorf("task %s not found", taskID)
} }
tr := &models.TaskResponse{ tr := &model.TaskResponse{
Automation: task.Automation, Automation: task.Automation,
Closed: task.Closed, Closed: task.Closed,
Created: task.Created, Created: task.Created,
@@ -67,7 +67,7 @@ func toTaskResponse(playbook *models.Playbook, taskID string, order int, graph *
return tr, nil return tr, nil
} }
func activePlaybook(playbook *models.Playbook, taskID string) (bool, error) { func activePlaybook(playbook *model.Playbook, taskID string) (bool, error) {
task, ok := playbook.Tasks[taskID] task, ok := playbook.Tasks[taskID]
if !ok { if !ok {
return false, fmt.Errorf("playbook does not contain tasks %s", taskID) return false, fmt.Errorf("playbook does not contain tasks %s", taskID)
@@ -81,7 +81,7 @@ func activePlaybook(playbook *models.Playbook, taskID string) (bool, error) {
return active(playbook, taskID, d, task) return active(playbook, taskID, d, task)
} }
func active(playbook *models.Playbook, taskID string, d *dag.Graph, task *models.Task) (bool, error) { func active(playbook *model.Playbook, taskID string, d *dag.Graph, task *model.Task) (bool, error) {
if task.Done { if task.Done {
return false, nil return false, nil
} }
@@ -165,7 +165,7 @@ func evalRequirement(aql string, data interface{}) (bool, error) {
/* /*
// "github.com/qri-io/jsonschema" // "github.com/qri-io/jsonschema"
func valid(task *models.Task) (bool, error) { func valid(task *model.Task) (bool, error) {
schema, err := json.Marshal(task.Schema) schema, err := json.Marshal(task.Schema)
if err != nil { if err != nil {
return false, err return false, err

View File

@@ -5,12 +5,12 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
var playbook2 = &models.Playbook{ var playbook2 = &model.Playbook{
Name: "Phishing", Name: "Phishing",
Tasks: map[string]*models.Task{ Tasks: map[string]*model.Task{
"board": {Next: map[string]string{ "board": {Next: map[string]string{
"escalate": "boardInvolved == true", "escalate": "boardInvolved == true",
"aquire-mail": "boardInvolved == false", "aquire-mail": "boardInvolved == false",
@@ -30,9 +30,9 @@ var playbook2 = &models.Playbook{
}, },
} }
var playbook3 = &models.Playbook{ var playbook3 = &model.Playbook{
Name: "Phishing", Name: "Phishing",
Tasks: map[string]*models.Task{ Tasks: map[string]*model.Task{
"board": {Next: map[string]string{ "board": {Next: map[string]string{
"escalate": "boardInvolved == true", "escalate": "boardInvolved == true",
"aquire-mail": "boardInvolved == false", "aquire-mail": "boardInvolved == false",
@@ -52,9 +52,9 @@ var playbook3 = &models.Playbook{
}, },
} }
var playbook4 = &models.Playbook{ var playbook4 = &model.Playbook{
Name: "Malware", Name: "Malware",
Tasks: map[string]*models.Task{ Tasks: map[string]*model.Task{
"file-or-hash": {Next: map[string]string{ "file-or-hash": {Next: map[string]string{
"enter-hash": "file == 'Hash'", "enter-hash": "file == 'Hash'",
"upload": "file == 'File'", "upload": "file == 'File'",
@@ -72,7 +72,7 @@ var playbook4 = &models.Playbook{
func Test_canBeCompleted(t *testing.T) { func Test_canBeCompleted(t *testing.T) {
type args struct { type args struct {
playbook *models.Playbook playbook *model.Playbook
taskID string taskID string
} }
tests := []struct { tests := []struct {
@@ -106,7 +106,7 @@ func Test_canBeCompleted(t *testing.T) {
func Test_playbookOrder(t *testing.T) { func Test_playbookOrder(t *testing.T) {
type args struct { type args struct {
playbook *models.Playbook playbook *model.Playbook
} }
tests := []struct { tests := []struct {
name string name string

View File

@@ -5,14 +5,13 @@ import (
"errors" "errors"
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func toUserDataResponse(key string, doc *models.UserData) *models.UserDataResponse { func toUserDataResponse(key string, doc *model.UserData) *model.UserDataResponse {
return &models.UserDataResponse{ return &model.UserDataResponse{
Email: doc.Email, Email: doc.Email,
ID: key, ID: key,
Image: doc.Image, Image: doc.Image,
@@ -21,7 +20,7 @@ func toUserDataResponse(key string, doc *models.UserData) *models.UserDataRespon
} }
} }
func (db *Database) UserDataCreate(ctx context.Context, id string, userdata *models.UserData) error { func (db *Database) UserDataCreate(ctx context.Context, id string, userdata *model.UserData) error {
if userdata == nil { if userdata == nil {
return errors.New("requires setting") return errors.New("requires setting")
} }
@@ -33,7 +32,7 @@ func (db *Database) UserDataCreate(ctx context.Context, id string, userdata *mod
return err return err
} }
func (db *Database) UserDataGetOrCreate(ctx *gin.Context, id string, newUserData *models.UserData) (*models.UserDataResponse, error) { func (db *Database) UserDataGetOrCreate(ctx context.Context, id string, newUserData *model.UserData) (*model.UserDataResponse, error) {
setting, err := db.UserDataGet(ctx, id) setting, err := db.UserDataGet(ctx, id)
if err != nil { if err != nil {
return toUserDataResponse(id, newUserData), db.UserDataCreate(ctx, id, newUserData) return toUserDataResponse(id, newUserData), db.UserDataCreate(ctx, id, newUserData)
@@ -41,8 +40,8 @@ func (db *Database) UserDataGetOrCreate(ctx *gin.Context, id string, newUserData
return setting, nil return setting, nil
} }
func (db *Database) UserDataGet(ctx context.Context, id string) (*models.UserDataResponse, error) { func (db *Database) UserDataGet(ctx context.Context, id string) (*model.UserDataResponse, error) {
var doc models.UserData var doc model.UserData
meta, err := db.userdataCollection.ReadDocument(ctx, id, &doc) meta, err := db.userdataCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -51,16 +50,16 @@ func (db *Database) UserDataGet(ctx context.Context, id string) (*models.UserDat
return toUserDataResponse(meta.Key, &doc), err return toUserDataResponse(meta.Key, &doc), err
} }
func (db *Database) UserDataList(ctx context.Context) ([]*models.UserDataResponse, error) { func (db *Database) UserDataList(ctx context.Context) ([]*model.UserDataResponse, error) {
query := "FOR d IN @@collection SORT d.username ASC RETURN d" query := "FOR d IN @@collection SORT d.username ASC RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserDataCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserDataCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.UserDataResponse var docs []*model.UserDataResponse
for { for {
var doc models.UserData var doc model.UserData
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break
@@ -73,8 +72,8 @@ func (db *Database) UserDataList(ctx context.Context) ([]*models.UserDataRespons
return docs, err return docs, err
} }
func (db *Database) UserDataUpdate(ctx context.Context, id string, userdata *models.UserData) (*models.UserDataResponse, error) { func (db *Database) UserDataUpdate(ctx context.Context, id string, userdata *model.UserData) (*model.UserDataResponse, error) {
var doc models.UserData var doc model.UserData
ctx = driver.WithReturnNew(ctx, &doc) ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.userdataCollection.ReplaceDocument(ctx, id, userdata) meta, err := db.userdataCollection.ReplaceDocument(ctx, id, userdata)

View File

@@ -3,24 +3,19 @@ package database_test
import ( import (
"testing" "testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/pointer" "github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/test" "github.com/SecurityBrewery/catalyst/test"
) )
func init() { var bob = &model.UserData{
gin.SetMode(gin.TestMode)
}
var bob = &models.UserData{
Email: pointer.String("bob@example.org"), Email: pointer.String("bob@example.org"),
Name: pointer.String("Bob"), Name: pointer.String("Bob"),
} }
var bobResponse = &models.UserDataResponse{ var bobResponse = &model.UserDataResponse{
ID: "bob", ID: "bob",
Email: pointer.String("bob@example.org"), Email: pointer.String("bob@example.org"),
Name: pointer.String("Bob"), Name: pointer.String("Bob"),
@@ -29,7 +24,7 @@ var bobResponse = &models.UserDataResponse{
func TestDatabase_UserDataCreate(t *testing.T) { func TestDatabase_UserDataCreate(t *testing.T) {
type args struct { type args struct {
id string id string
setting *models.UserData setting *model.UserData
} }
tests := []struct { tests := []struct {
name string name string
@@ -63,7 +58,7 @@ func TestDatabase_UserDataGet(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
args args args args
want *models.UserDataResponse want *model.UserDataResponse
wantErr bool wantErr bool
}{ }{
{name: "Normal get", args: args{id: "bob"}, want: bobResponse}, {name: "Normal get", args: args{id: "bob"}, want: bobResponse},
@@ -98,10 +93,10 @@ func TestDatabase_UserDataGet(t *testing.T) {
func TestDatabase_UserDataList(t *testing.T) { func TestDatabase_UserDataList(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
want []*models.UserDataResponse want []*model.UserDataResponse
wantErr bool wantErr bool
}{ }{
{name: "Normal list", want: []*models.UserDataResponse{bobResponse}}, {name: "Normal list", want: []*model.UserDataResponse{bobResponse}},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@@ -129,7 +124,7 @@ func TestDatabase_UserDataList(t *testing.T) {
func TestDatabase_UserDataUpdate(t *testing.T) { func TestDatabase_UserDataUpdate(t *testing.T) {
type args struct { type args struct {
id string id string
setting *models.UserData setting *model.UserData
} }
tests := []struct { tests := []struct {
name string name string

View File

@@ -4,10 +4,10 @@ import (
"context" "context"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func (db *Database) Statistics(ctx context.Context) (*models.Statistics, error) { func (db *Database) Statistics(ctx context.Context) (*model.Statistics, error) {
query := `RETURN { query := `RETURN {
tickets_per_type: MERGE(FOR d in tickets tickets_per_type: MERGE(FOR d in tickets
COLLECT type = d.type WITH COUNT INTO typecount COLLECT type = d.type WITH COUNT INTO typecount
@@ -34,7 +34,7 @@ func (db *Database) Statistics(ctx context.Context) (*models.Statistics, error)
} }
defer cur.Close() defer cur.Close()
statistics := models.Statistics{} statistics := model.Statistics{}
if _, err := cur.ReadDocument(ctx, &statistics); err != nil { if _, err := cur.ReadDocument(ctx, &statistics); err != nil {
return nil, err return nil, err
} }

View File

@@ -6,18 +6,18 @@ import (
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
type playbookResponse struct { type playbookResponse struct {
PlaybookId string `json:"playbook_id"` PlaybookId string `json:"playbook_id"`
PlaybookName string `json:"playbook_name"` PlaybookName string `json:"playbook_name"`
Playbook models.Playbook `json:"playbook"` Playbook model.Playbook `json:"playbook"`
TicketId int64 `json:"ticket_id"` TicketId int64 `json:"ticket_id"`
TicketName string `json:"ticket_name"` TicketName string `json:"ticket_name"`
} }
func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, error) { func (db *Database) TaskList(ctx context.Context) ([]*model.TaskWithContext, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -35,7 +35,7 @@ func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, er
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
docs := []*models.TaskWithContext{} var docs []*model.TaskWithContext
for { for {
var doc playbookResponse var doc playbookResponse
_, err := cursor.ReadDocument(ctx, &doc) _, err := cursor.ReadDocument(ctx, &doc)
@@ -45,7 +45,6 @@ func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, er
return nil, err return nil, err
} }
playbook, err := toPlaybookResponse(&doc.Playbook) playbook, err := toPlaybookResponse(&doc.Playbook)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -53,10 +52,10 @@ func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, er
for _, task := range playbook.Tasks { for _, task := range playbook.Tasks {
if task.Active { if task.Active {
docs = append(docs, &models.TaskWithContext{ docs = append(docs, &model.TaskWithContext{
PlaybookId: doc.PlaybookId, PlaybookId: doc.PlaybookId,
PlaybookName: doc.PlaybookName, PlaybookName: doc.PlaybookName,
Task: *task, Task: task,
TicketId: doc.TicketId, TicketId: doc.TicketId,
TicketName: doc.TicketName, TicketName: doc.TicketName,
}) })

View File

@@ -8,18 +8,18 @@ import (
"github.com/iancoleman/strcase" "github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func toTicketTemplate(doc *models.TicketTemplateForm) *models.TicketTemplate { func toTicketTemplate(doc *model.TicketTemplateForm) *model.TicketTemplate {
return &models.TicketTemplate{Name: doc.Name, Schema: doc.Schema} return &model.TicketTemplate{Name: doc.Name, Schema: doc.Schema}
} }
func toTicketTemplateResponse(key string, doc *models.TicketTemplate) *models.TicketTemplateResponse { func toTicketTemplateResponse(key string, doc *model.TicketTemplate) *model.TicketTemplateResponse {
return &models.TicketTemplateResponse{ID: key, Name: doc.Name, Schema: doc.Schema} return &model.TicketTemplateResponse{ID: key, Name: doc.Name, Schema: doc.Schema}
} }
func (db *Database) TemplateCreate(ctx context.Context, template *models.TicketTemplateForm) (*models.TicketTemplateResponse, error) { func (db *Database) TemplateCreate(ctx context.Context, template *model.TicketTemplateForm) (*model.TicketTemplateResponse, error) {
if template == nil { if template == nil {
return nil, errors.New("requires template") return nil, errors.New("requires template")
} }
@@ -27,7 +27,7 @@ func (db *Database) TemplateCreate(ctx context.Context, template *models.TicketT
return nil, errors.New("requires template name") return nil, errors.New("requires template name")
} }
var doc models.TicketTemplate var doc model.TicketTemplate
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.templateCollection.CreateDocument(ctx, newctx, strcase.ToKebab(template.Name), toTicketTemplate(template)) meta, err := db.templateCollection.CreateDocument(ctx, newctx, strcase.ToKebab(template.Name), toTicketTemplate(template))
@@ -38,8 +38,8 @@ func (db *Database) TemplateCreate(ctx context.Context, template *models.TicketT
return toTicketTemplateResponse(meta.Key, &doc), nil return toTicketTemplateResponse(meta.Key, &doc), nil
} }
func (db *Database) TemplateGet(ctx context.Context, id string) (*models.TicketTemplateResponse, error) { func (db *Database) TemplateGet(ctx context.Context, id string) (*model.TicketTemplateResponse, error) {
var doc models.TicketTemplate var doc model.TicketTemplate
meta, err := db.templateCollection.ReadDocument(ctx, id, &doc) meta, err := db.templateCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -48,8 +48,8 @@ func (db *Database) TemplateGet(ctx context.Context, id string) (*models.TicketT
return toTicketTemplateResponse(meta.Key, &doc), nil return toTicketTemplateResponse(meta.Key, &doc), nil
} }
func (db *Database) TemplateUpdate(ctx context.Context, id string, template *models.TicketTemplateForm) (*models.TicketTemplateResponse, error) { func (db *Database) TemplateUpdate(ctx context.Context, id string, template *model.TicketTemplateForm) (*model.TicketTemplateResponse, error) {
var doc models.TicketTemplate var doc model.TicketTemplate
ctx = driver.WithReturnNew(ctx, &doc) ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.templateCollection.ReplaceDocument(ctx, id, toTicketTemplate(template)) meta, err := db.templateCollection.ReplaceDocument(ctx, id, toTicketTemplate(template))
@@ -65,16 +65,16 @@ func (db *Database) TemplateDelete(ctx context.Context, id string) error {
return err return err
} }
func (db *Database) TemplateList(ctx context.Context) ([]*models.TicketTemplateResponse, error) { func (db *Database) TemplateList(ctx context.Context) ([]*model.TicketTemplateResponse, error) {
query := "FOR d IN @@collection RETURN d" query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": TemplateCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": TemplateCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.TicketTemplateResponse var docs []*model.TicketTemplateResponse
for { for {
var doc models.TicketTemplate var doc model.TicketTemplate
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break

View File

@@ -6,22 +6,22 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/SecurityBrewery/catalyst/database/migrations" "github.com/SecurityBrewery/catalyst/database/migrations"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/test" "github.com/SecurityBrewery/catalyst/test"
) )
var template1 = &models.TicketTemplateForm{ var template1 = &model.TicketTemplateForm{
Schema: migrations.DefaultTemplateSchema, Schema: migrations.DefaultTemplateSchema,
Name: "Template 1", Name: "Template 1",
} }
var default1 = &models.TicketTemplateForm{ var default1 = &model.TicketTemplateForm{
Schema: migrations.DefaultTemplateSchema, Schema: migrations.DefaultTemplateSchema,
Name: "Default", Name: "Default",
} }
func TestDatabase_TemplateCreate(t *testing.T) { func TestDatabase_TemplateCreate(t *testing.T) {
type args struct { type args struct {
template *models.TicketTemplateForm template *model.TicketTemplateForm
} }
tests := []struct { tests := []struct {
name string name string
@@ -31,8 +31,8 @@ func TestDatabase_TemplateCreate(t *testing.T) {
{name: "Normal", args: args{template: template1}}, {name: "Normal", args: args{template: template1}},
{name: "Duplicate", args: args{template: default1}, wantErr: true}, {name: "Duplicate", args: args{template: default1}, wantErr: true},
{name: "Nil template", args: args{}, wantErr: true}, {name: "Nil template", args: args{}, wantErr: true},
{name: "Template without fields", args: args{template: &models.TicketTemplateForm{}}, wantErr: true}, {name: "Template without fields", args: args{template: &model.TicketTemplateForm{}}, wantErr: true},
{name: "Only name", args: args{template: &models.TicketTemplateForm{Name: "name"}}, wantErr: false}, {name: "Only name", args: args{template: &model.TicketTemplateForm{Name: "name"}}, wantErr: false},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@@ -87,10 +87,10 @@ func TestDatabase_TemplateGet(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
args args args args
want *models.TicketTemplateResponse want *model.TicketTemplateResponse
wantErr bool wantErr bool
}{ }{
{name: "Normal", args: args{id: "default"}, want: &models.TicketTemplateResponse{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}}, {name: "Normal", args: args{id: "default"}, want: &model.TicketTemplateResponse{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}},
{name: "Not existing", args: args{id: "foobar"}, wantErr: true}, {name: "Not existing", args: args{id: "foobar"}, wantErr: true},
} }
for _, tt := range tests { for _, tt := range tests {
@@ -122,10 +122,10 @@ func TestDatabase_TemplateGet(t *testing.T) {
func TestDatabase_TemplateList(t *testing.T) { func TestDatabase_TemplateList(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
want []*models.TicketTemplateResponse want []*model.TicketTemplateResponse
wantErr bool wantErr bool
}{ }{
{name: "Normal", want: []*models.TicketTemplateResponse{{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}, {ID: "template-1", Name: template1.Name, Schema: template1.Schema}}}, {name: "Normal", want: []*model.TicketTemplateResponse{{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}, {ID: "template-1", Name: template1.Name, Schema: template1.Schema}}},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@@ -152,7 +152,7 @@ func TestDatabase_TemplateList(t *testing.T) {
func TestDatabase_TemplateUpdate(t *testing.T) { func TestDatabase_TemplateUpdate(t *testing.T) {
type args struct { type args struct {
id string id string
template *models.TicketTemplateForm template *model.TicketTemplateForm
} }
tests := []struct { tests := []struct {
name string name string

View File

@@ -16,18 +16,18 @@ import (
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/caql" "github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/index" "github.com/SecurityBrewery/catalyst/index"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
func toTicket(ticketForm *models.TicketForm) (interface{}, error) { func toTicket(ticketForm *model.TicketForm) (interface{}, error) {
playbooks, err := toPlaybooks(ticketForm.Playbooks) playbooks, err := toPlaybooks(ticketForm.Playbooks)
if err != nil { if err != nil {
return nil, err return nil, err
} }
ticket := &models.Ticket{ ticket := &model.Ticket{
Artifacts: ticketForm.Artifacts, Artifacts: ticketForm.Artifacts,
Comments: ticketForm.Comments, Comments: ticketForm.Comments,
Details: ticketForm.Details, Details: ticketForm.Details,
@@ -70,8 +70,8 @@ func toTicket(ticketForm *models.TicketForm) (interface{}, error) {
return ticket, nil return ticket, nil
} }
func toTicketResponses(tickets []*models.TicketSimpleResponse) ([]*models.TicketResponse, error) { func toTicketResponses(tickets []*model.TicketSimpleResponse) ([]*model.TicketResponse, error) {
var extendedTickets []*models.TicketResponse var extendedTickets []*model.TicketResponse
for _, simple := range tickets { for _, simple := range tickets {
tr, err := toTicketResponse(simple) tr, err := toTicketResponse(simple)
if err != nil { if err != nil {
@@ -82,13 +82,13 @@ func toTicketResponses(tickets []*models.TicketSimpleResponse) ([]*models.Ticket
return extendedTickets, nil return extendedTickets, nil
} }
func toTicketResponse(ticket *models.TicketSimpleResponse) (*models.TicketResponse, error) { func toTicketResponse(ticket *model.TicketSimpleResponse) (*model.TicketResponse, error) {
playbooks, err := toPlaybookResponses(ticket.Playbooks) playbooks, err := toPlaybookResponses(ticket.Playbooks)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &models.TicketResponse{ return &model.TicketResponse{
ID: ticket.ID, ID: ticket.ID,
Artifacts: ticket.Artifacts, Artifacts: ticket.Artifacts,
Comments: ticket.Comments, Comments: ticket.Comments,
@@ -108,13 +108,13 @@ func toTicketResponse(ticket *models.TicketSimpleResponse) (*models.TicketRespon
}, nil }, nil
} }
func toTicketSimpleResponse(key string, ticket *models.Ticket) (*models.TicketSimpleResponse, error) { func toTicketSimpleResponse(key string, ticket *model.Ticket) (*model.TicketSimpleResponse, error) {
id, err := strconv.ParseInt(key, 10, 64) id, err := strconv.ParseInt(key, 10, 64)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &models.TicketSimpleResponse{ return &model.TicketSimpleResponse{
Artifacts: ticket.Artifacts, Artifacts: ticket.Artifacts,
Comments: ticket.Comments, Comments: ticket.Comments,
Created: ticket.Created, Created: ticket.Created,
@@ -134,8 +134,8 @@ func toTicketSimpleResponse(key string, ticket *models.Ticket) (*models.TicketSi
}, nil }, nil
} }
func toTicketWithTickets(ticketResponse *models.TicketResponse, tickets []*models.TicketSimpleResponse, logs []*models.LogEntry) *models.TicketWithTickets { func toTicketWithTickets(ticketResponse *model.TicketResponse, tickets []*model.TicketSimpleResponse, logs []*model.LogEntry) *model.TicketWithTickets {
return &models.TicketWithTickets{ return &model.TicketWithTickets{
Artifacts: ticketResponse.Artifacts, Artifacts: ticketResponse.Artifacts,
Comments: ticketResponse.Comments, Comments: ticketResponse.Comments,
Created: ticketResponse.Created, Created: ticketResponse.Created,
@@ -158,8 +158,8 @@ func toTicketWithTickets(ticketResponse *models.TicketResponse, tickets []*model
} }
} }
func toPlaybookResponses(playbooks map[string]*models.Playbook) (map[string]*models.PlaybookResponse, error) { func toPlaybookResponses(playbooks map[string]*model.Playbook) (map[string]*model.PlaybookResponse, error) {
pr := map[string]*models.PlaybookResponse{} pr := map[string]*model.PlaybookResponse{}
var err error var err error
for k, v := range playbooks { for k, v := range playbooks {
pr[k], err = toPlaybookResponse(v) pr[k], err = toPlaybookResponse(v)
@@ -170,15 +170,15 @@ func toPlaybookResponses(playbooks map[string]*models.Playbook) (map[string]*mod
return pr, nil return pr, nil
} }
func toPlaybookResponse(playbook *models.Playbook) (*models.PlaybookResponse, error) { func toPlaybookResponse(playbook *model.Playbook) (*model.PlaybookResponse, error) {
graph, err := playbookGraph(playbook) graph, err := playbookGraph(playbook)
if err != nil { if err != nil {
return nil, err return nil, err
} }
re := &models.PlaybookResponse{ re := &model.PlaybookResponse{
Name: playbook.Name, Name: playbook.Name,
Tasks: map[string]*models.TaskResponse{}, Tasks: map[string]*model.TaskResponse{},
} }
results, err := graph.Toposort() results, err := graph.Toposort()
@@ -198,7 +198,7 @@ func toPlaybookResponse(playbook *models.Playbook) (*models.PlaybookResponse, er
return re, nil return re, nil
} }
func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*models.TicketForm) ([]*models.TicketResponse, error) { func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*model.TicketForm) ([]*model.TicketResponse, error) {
update, err := db.Hooks.IngestionFilter(ctx, db.Index) update, err := db.Hooks.IngestionFilter(ctx, db.Index)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -211,7 +211,7 @@ func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*models
return nil, err return nil, err
} }
if err := validate(ticket, models.TicketSchema); err != nil { if err := validate(ticket, model.TicketSchema); err != nil {
return nil, err return nil, err
} }
@@ -278,26 +278,26 @@ func (db *Database) IndexRebuild(ctx context.Context) error {
return batchIndex(db.Index, tickets) return batchIndex(db.Index, tickets)
} }
func batchIndex(index *index.Index, tickets []*models.TicketSimpleResponse) error { func batchIndex(index *index.Index, tickets []*model.TicketSimpleResponse) error {
var wg sync.WaitGroup var wg sync.WaitGroup
var batch []*models.TicketSimpleResponse var batch []*model.TicketSimpleResponse
for _, ticket := range tickets { for _, ticket := range tickets {
batch = append(batch, ticket) batch = append(batch, ticket)
if len(batch) > 100 { if len(batch) > 100 {
wg.Add(1) wg.Add(1)
go func(docs []*models.TicketSimpleResponse) { go func(docs []*model.TicketSimpleResponse) {
index.Index(docs) index.Index(docs)
wg.Done() wg.Done()
}(batch) }(batch)
batch = []*models.TicketSimpleResponse{} batch = []*model.TicketSimpleResponse{}
} }
} }
wg.Wait() wg.Wait()
return nil return nil
} }
func (db *Database) TicketGet(ctx context.Context, ticketID int64) (*models.TicketWithTickets, error) { func (db *Database) TicketGet(ctx context.Context, ticketID int64) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketReadFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketReadFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -306,7 +306,7 @@ func (db *Database) TicketGet(ctx context.Context, ticketID int64) (*models.Tick
return db.ticketGetQuery(ctx, ticketID, `LET d = DOCUMENT(@@collection, @ID) `+ticketFilterQuery+` RETURN d`, ticketFilterVars, busdb.ReadOperation) return db.ticketGetQuery(ctx, ticketID, `LET d = DOCUMENT(@@collection, @ID) `+ticketFilterQuery+` RETURN d`, ticketFilterVars, busdb.ReadOperation)
} }
func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query string, bindVars map[string]interface{}, operation *busdb.Operation) (*models.TicketWithTickets, error) { func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query string, bindVars map[string]interface{}, operation *busdb.Operation) (*model.TicketWithTickets, error) {
if bindVars == nil { if bindVars == nil {
bindVars = map[string]interface{}{} bindVars = map[string]interface{}{}
} }
@@ -321,7 +321,7 @@ func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query st
} }
defer cur.Close() defer cur.Close()
ticket := models.Ticket{} ticket := model.Ticket{}
meta, err := cur.ReadDocument(ctx, &ticket) meta, err := cur.ReadDocument(ctx, &ticket)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -333,7 +333,7 @@ func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query st
} }
// index // index
go db.Index.Index([]*models.TicketSimpleResponse{ticketSimpleResponse}) go db.Index.Index([]*model.TicketSimpleResponse{ticketSimpleResponse})
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketReadFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketReadFilter(ctx)
if err != nil { if err != nil {
@@ -414,7 +414,7 @@ func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query st
return toTicketWithTickets(ticketResponse, tickets, logs), nil return toTicketWithTickets(ticketResponse, tickets, logs), nil
} }
func (db *Database) TicketUpdate(ctx context.Context, ticketID int64, ticket *models.Ticket) (*models.TicketWithTickets, error) { func (db *Database) TicketUpdate(ctx context.Context, ticketID int64, ticket *model.Ticket) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -446,7 +446,7 @@ func (db *Database) TicketDelete(ctx context.Context, ticketID int64) error {
return nil return nil
} }
func (db *Database) TicketList(ctx context.Context, ticketType string, query string, sorts []string, desc []bool, offset, count int64) (*models.TicketList, error) { func (db *Database) TicketList(ctx context.Context, ticketType string, query string, sorts []string, desc []bool, offset, count int64) (*model.TicketList, error) {
binVars := map[string]interface{}{} binVars := map[string]interface{}{}
parser := &caql.Parser{Searcher: db.Index, Prefix: "d."} parser := &caql.Parser{Searcher: db.Index, Prefix: "d."}
@@ -494,14 +494,14 @@ func (db *Database) TicketList(ctx context.Context, ticketType string, query str
RETURN d` RETURN d`
// RETURN KEEP(d, "_key", "id", "name", "type", "created")` // RETURN KEEP(d, "_key", "id", "name", "type", "created")`
ticketList, _, err := db.ticketListQuery(ctx, q, mergeMaps(binVars, ticketFilterVars), busdb.ReadOperation) ticketList, _, err := db.ticketListQuery(ctx, q, mergeMaps(binVars, ticketFilterVars), busdb.ReadOperation)
return &models.TicketList{ return &model.TicketList{
Count: documentCount, Count: documentCount,
Tickets: ticketList, Tickets: ticketList,
}, err }, err
// return map[string]interface{}{"tickets": ticketList, "count": documentCount}, err // return map[string]interface{}{"tickets": ticketList, "count": documentCount}, err
} }
func (db *Database) ticketListQuery(ctx context.Context, query string, bindVars map[string]interface{}, operation *busdb.Operation) ([]*models.TicketSimpleResponse, *models.LogEntry, error) { func (db *Database) ticketListQuery(ctx context.Context, query string, bindVars map[string]interface{}, operation *busdb.Operation) ([]*model.TicketSimpleResponse, *model.LogEntry, error) {
if bindVars == nil { if bindVars == nil {
bindVars = map[string]interface{}{} bindVars = map[string]interface{}{}
} }
@@ -513,9 +513,9 @@ func (db *Database) ticketListQuery(ctx context.Context, query string, bindVars
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.TicketSimpleResponse var docs []*model.TicketSimpleResponse
for { for {
doc := models.Ticket{} doc := model.Ticket{}
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break

View File

@@ -11,12 +11,12 @@ import (
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/pointer" "github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
func (db *Database) AddArtifact(ctx context.Context, id int64, artifact *models.Artifact) (*models.TicketWithTickets, error) { func (db *Database) AddArtifact(ctx context.Context, id int64, artifact *model.Artifact) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -60,7 +60,7 @@ func inferType(name string) string {
return "unknown" return "unknown"
} }
func (db *Database) RemoveArtifact(ctx context.Context, id int64, name string) (*models.TicketWithTickets, error) { func (db *Database) RemoveArtifact(ctx context.Context, id int64, name string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -81,7 +81,7 @@ func (db *Database) RemoveArtifact(ctx context.Context, id int64, name string) (
}) })
} }
func (db *Database) SetTemplate(ctx context.Context, id int64, schema string) (*models.TicketWithTickets, error) { func (db *Database) SetTemplate(ctx context.Context, id int64, schema string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -99,7 +99,7 @@ func (db *Database) SetTemplate(ctx context.Context, id int64, schema string) (*
}) })
} }
func (db *Database) AddComment(ctx context.Context, id int64, comment *models.CommentForm) (*models.TicketWithTickets, error) { func (db *Database) AddComment(ctx context.Context, id int64, comment *model.CommentForm) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -130,7 +130,7 @@ func (db *Database) AddComment(ctx context.Context, id int64, comment *models.Co
}) })
} }
func (db *Database) RemoveComment(ctx context.Context, id int64, commentID int64) (*models.TicketWithTickets, error) { func (db *Database) RemoveComment(ctx context.Context, id int64, commentID int64) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -148,7 +148,7 @@ func (db *Database) RemoveComment(ctx context.Context, id int64, commentID int64
}) })
} }
func (db *Database) SetReferences(ctx context.Context, id int64, references []*models.Reference) (*models.TicketWithTickets, error) { func (db *Database) SetReferences(ctx context.Context, id int64, references []*model.Reference) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -166,7 +166,7 @@ func (db *Database) SetReferences(ctx context.Context, id int64, references []*m
}) })
} }
func (db *Database) LinkFiles(ctx context.Context, id int64, files []*models.File) (*models.TicketWithTickets, error) { func (db *Database) LinkFiles(ctx context.Context, id int64, files []*model.File) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -184,7 +184,7 @@ func (db *Database) LinkFiles(ctx context.Context, id int64, files []*models.Fil
}) })
} }
func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTemplate *models.PlaybookTemplateForm) (*models.TicketWithTickets, error) { func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTemplate *model.PlaybookTemplateForm) (*model.TicketWithTickets, error) {
pb, err := toPlaybook(playbookTemplate) pb, err := toPlaybook(playbookTemplate)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -234,7 +234,7 @@ func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTem
return ticket, nil return ticket, nil
} }
func findName(playbooks map[string]*models.PlaybookResponse, name string) string { func findName(playbooks map[string]*model.PlaybookResponse, name string) string {
if _, ok := playbooks[name]; !ok { if _, ok := playbooks[name]; !ok {
return name return name
} }
@@ -247,10 +247,10 @@ func findName(playbooks map[string]*models.PlaybookResponse, name string) string
} }
} }
func runRootTask(ticket *models.TicketResponse, playbookID string, db *Database) error { func runRootTask(ticket *model.TicketResponse, playbookID string, db *Database) error {
playbook := ticket.Playbooks[playbookID] playbook := ticket.Playbooks[playbookID]
var root *models.TaskResponse var root *model.TaskResponse
for _, task := range playbook.Tasks { for _, task := range playbook.Tasks {
if task.Order == 0 { if task.Order == 0 {
root = task root = task
@@ -261,7 +261,7 @@ func runRootTask(ticket *models.TicketResponse, playbookID string, db *Database)
return nil return nil
} }
func (db *Database) RemoveTicketPlaybook(ctx context.Context, id int64, playbookID string) (*models.TicketWithTickets, error) { func (db *Database) RemoveTicketPlaybook(ctx context.Context, id int64, playbookID string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@@ -11,11 +11,11 @@ import (
"github.com/SecurityBrewery/catalyst/bus" "github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
) )
func (db *Database) TaskGet(ctx context.Context, id int64, playbookID string, taskID string) (*models.TicketWithTickets, *models.PlaybookResponse, *models.TaskWithContext, error) { func (db *Database) TaskGet(ctx context.Context, id int64, playbookID string, taskID string) (*model.TicketWithTickets, *model.PlaybookResponse, *model.TaskWithContext, error) {
inc, err := db.TicketGet(ctx, id) inc, err := db.TicketGet(ctx, id)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
@@ -31,17 +31,17 @@ func (db *Database) TaskGet(ctx context.Context, id int64, playbookID string, ta
return nil, nil, nil, errors.New("task does not exist") return nil, nil, nil, errors.New("task does not exist")
} }
return inc, playbook, &models.TaskWithContext{ return inc, playbook, &model.TaskWithContext{
PlaybookId: playbookID, PlaybookId: playbookID,
PlaybookName: playbook.Name, PlaybookName: playbook.Name,
TaskId: taskID, TaskId: taskID,
Task: *task, Task: task,
TicketId: id, TicketId: id,
TicketName: inc.Name, TicketName: inc.Name,
}, nil }, nil
} }
func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID string, taskID string, data interface{}) (*models.TicketWithTickets, error) { func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID string, taskID string, data interface{}) (*model.TicketWithTickets, error) {
inc, err := db.TicketGet(ctx, id) inc, err := db.TicketGet(ctx, id)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -92,8 +92,8 @@ func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID strin
return ticket, nil return ticket, nil
} }
func extractTicketResponse(ticket *models.TicketWithTickets) *models.TicketResponse { func extractTicketResponse(ticket *model.TicketWithTickets) *model.TicketResponse {
return &models.TicketResponse{ return &model.TicketResponse{
Artifacts: ticket.Artifacts, Artifacts: ticket.Artifacts,
Comments: ticket.Comments, Comments: ticket.Comments,
Created: ticket.Created, Created: ticket.Created,
@@ -113,7 +113,7 @@ func extractTicketResponse(ticket *models.TicketWithTickets) *models.TicketRespo
} }
} }
func (db *Database) TaskUpdate(ctx context.Context, id int64, playbookID string, taskID string, task *models.Task) (*models.TicketWithTickets, error) { func (db *Database) TaskUpdate(ctx context.Context, id int64, playbookID string, taskID string, task *model.Task) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx) ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -154,8 +154,8 @@ func (db *Database) TaskRun(ctx context.Context, id int64, playbookID string, ta
return err return err
} }
if task.Task.Type == models.TaskTypeAutomation { if task.Task.Type == model.TaskTypeAutomation {
if err := runTask(id, playbookID, taskID, &task.Task, extractTicketResponse(ticket), db); err != nil { if err := runTask(id, playbookID, taskID, task.Task, extractTicketResponse(ticket), db); err != nil {
return err return err
} }
} }
@@ -163,10 +163,10 @@ func (db *Database) TaskRun(ctx context.Context, id int64, playbookID string, ta
return nil return nil
} }
func runNextTasks(id int64, playbookID string, next map[string]string, data interface{}, ticket *models.TicketResponse, db *Database) { func runNextTasks(id int64, playbookID string, next map[string]string, data interface{}, ticket *model.TicketResponse, db *Database) {
for nextTaskID, requirement := range next { for nextTaskID, requirement := range next {
nextTask := ticket.Playbooks[playbookID].Tasks[nextTaskID] nextTask := ticket.Playbooks[playbookID].Tasks[nextTaskID]
if nextTask.Type == models.TaskTypeAutomation { if nextTask.Type == model.TaskTypeAutomation {
b, err := evalRequirement(requirement, data) b, err := evalRequirement(requirement, data)
if err != nil { if err != nil {
continue continue
@@ -180,10 +180,10 @@ func runNextTasks(id int64, playbookID string, next map[string]string, data inte
} }
} }
func runTask(ticketID int64, playbookID string, taskID string, task *models.TaskResponse, ticket *models.TicketResponse, db *Database) error { func runTask(ticketID int64, playbookID string, taskID string, task *model.TaskResponse, ticket *model.TicketResponse, db *Database) error {
playbook := ticket.Playbooks[playbookID] playbook := ticket.Playbooks[playbookID]
msgContext := &models.Context{Playbook: playbook, Task: task, Ticket: ticket} msgContext := &model.Context{Playbook: playbook, Task: task, Ticket: ticket}
origin := &models.Origin{TaskOrigin: &models.TaskOrigin{TaskId: taskID, PlaybookId: playbookID, TicketId: ticketID}} origin := &model.Origin{TaskOrigin: &model.TaskOrigin{TaskId: taskID, PlaybookId: playbookID, TicketId: ticketID}}
jobID := uuid.NewString() jobID := uuid.NewString()
return publishJobMapping(jobID, *task.Automation, msgContext, origin, task.Payload, db) return publishJobMapping(jobID, *task.Automation, msgContext, origin, task.Payload, db)
} }

View File

@@ -8,11 +8,11 @@ import (
"github.com/iancoleman/strcase" "github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
) )
func toTicketType(doc *models.TicketTypeForm) *models.TicketType { func toTicketType(doc *model.TicketTypeForm) *model.TicketType {
return &models.TicketType{ return &model.TicketType{
Name: doc.Name, Name: doc.Name,
Icon: doc.Icon, Icon: doc.Icon,
DefaultPlaybooks: doc.DefaultPlaybooks, DefaultPlaybooks: doc.DefaultPlaybooks,
@@ -21,8 +21,8 @@ func toTicketType(doc *models.TicketTypeForm) *models.TicketType {
} }
} }
func toTicketTypeResponse(key string, doc *models.TicketType) *models.TicketTypeResponse { func toTicketTypeResponse(key string, doc *model.TicketType) *model.TicketTypeResponse {
return &models.TicketTypeResponse{ return &model.TicketTypeResponse{
ID: key, ID: key,
Name: doc.Name, Name: doc.Name,
Icon: doc.Icon, Icon: doc.Icon,
@@ -32,7 +32,7 @@ func toTicketTypeResponse(key string, doc *models.TicketType) *models.TicketType
} }
} }
func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *models.TicketTypeForm) (*models.TicketTypeResponse, error) { func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *model.TicketTypeForm) (*model.TicketTypeResponse, error) {
if tickettype == nil { if tickettype == nil {
return nil, errors.New("requires ticket type") return nil, errors.New("requires ticket type")
} }
@@ -40,7 +40,7 @@ func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *models.Tic
return nil, errors.New("requires ticket type name") return nil, errors.New("requires ticket type name")
} }
var doc models.TicketType var doc model.TicketType
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.tickettypeCollection.CreateDocument(ctx, newctx, strcase.ToKebab(tickettype.Name), toTicketType(tickettype)) meta, err := db.tickettypeCollection.CreateDocument(ctx, newctx, strcase.ToKebab(tickettype.Name), toTicketType(tickettype))
@@ -51,8 +51,8 @@ func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *models.Tic
return toTicketTypeResponse(meta.Key, &doc), nil return toTicketTypeResponse(meta.Key, &doc), nil
} }
func (db *Database) TicketTypeGet(ctx context.Context, id string) (*models.TicketTypeResponse, error) { func (db *Database) TicketTypeGet(ctx context.Context, id string) (*model.TicketTypeResponse, error) {
var doc models.TicketType var doc model.TicketType
meta, err := db.tickettypeCollection.ReadDocument(ctx, id, &doc) meta, err := db.tickettypeCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -61,8 +61,8 @@ func (db *Database) TicketTypeGet(ctx context.Context, id string) (*models.Ticke
return toTicketTypeResponse(meta.Key, &doc), nil return toTicketTypeResponse(meta.Key, &doc), nil
} }
func (db *Database) TicketTypeUpdate(ctx context.Context, id string, tickettype *models.TicketTypeForm) (*models.TicketTypeResponse, error) { func (db *Database) TicketTypeUpdate(ctx context.Context, id string, tickettype *model.TicketTypeForm) (*model.TicketTypeResponse, error) {
var doc models.TicketType var doc model.TicketType
ctx = driver.WithReturnNew(ctx, &doc) ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.tickettypeCollection.ReplaceDocument(ctx, id, toTicketType(tickettype)) meta, err := db.tickettypeCollection.ReplaceDocument(ctx, id, toTicketType(tickettype))
@@ -78,16 +78,16 @@ func (db *Database) TicketTypeDelete(ctx context.Context, id string) error {
return err return err
} }
func (db *Database) TicketTypeList(ctx context.Context) ([]*models.TicketTypeResponse, error) { func (db *Database) TicketTypeList(ctx context.Context) ([]*model.TicketTypeResponse, error) {
query := "FOR d IN @@collection RETURN d" query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": TicketTypeCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": TicketTypeCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.TicketTypeResponse var docs []*model.TicketTypeResponse
for { for {
var doc models.TicketType var doc model.TicketType
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break

View File

@@ -8,11 +8,10 @@ import (
"math/rand" "math/rand"
"github.com/arangodb/go-driver" "github.com/arangodb/go-driver"
"github.com/gin-gonic/gin"
"github.com/iancoleman/strcase" "github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/database/busdb" "github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models" "github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/pointer" "github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/role" "github.com/SecurityBrewery/catalyst/role"
"github.com/SecurityBrewery/catalyst/time" "github.com/SecurityBrewery/catalyst/time"
@@ -32,10 +31,10 @@ func generateKey() string {
return string(b) return string(b)
} }
func toUser(user *models.UserForm, sha256 *string) *models.User { func toUser(user *model.UserForm, sha256 *string) *model.User {
roles := []string{} roles := []string{}
roles = append(roles, role.Strings(role.Explodes(user.Roles))...) roles = append(roles, role.Strings(role.Explodes(user.Roles))...)
u := &models.User{ u := &model.User{
Blocked: user.Blocked, Blocked: user.Blocked,
Roles: roles, Roles: roles,
Sha256: sha256, Sha256: sha256,
@@ -45,7 +44,7 @@ func toUser(user *models.UserForm, sha256 *string) *models.User {
// log.Println(u) // log.Println(u)
// b, _ := json.Marshal(u) // b, _ := json.Marshal(u)
// loader := gojsonschema.NewBytesLoader(b) // loader := gojsonschema.NewBytesLoader(b)
// res, err := models.UserSchema.Validate(loader) // res, err := model.UserSchema.Validate(loader)
// if err != nil { // if err != nil {
// log.Println(err) // log.Println(err)
// } // }
@@ -54,8 +53,8 @@ func toUser(user *models.UserForm, sha256 *string) *models.User {
return u return u
} }
func toUserResponse(key string, user *models.User) *models.UserResponse { func toUserResponse(key string, user *model.User) *model.UserResponse {
return &models.UserResponse{ return &model.UserResponse{
ID: key, ID: key,
Roles: user.Roles, Roles: user.Roles,
Blocked: user.Blocked, Blocked: user.Blocked,
@@ -63,8 +62,8 @@ func toUserResponse(key string, user *models.User) *models.UserResponse {
} }
} }
func toNewUserResponse(key string, user *models.User, secret *string) *models.NewUserResponse { func toNewUserResponse(key string, user *model.User, secret *string) *model.NewUserResponse {
return &models.NewUserResponse{ return &model.NewUserResponse{
ID: key, ID: key,
Roles: user.Roles, Roles: user.Roles,
Secret: secret, Secret: secret,
@@ -72,19 +71,19 @@ func toNewUserResponse(key string, user *models.User, secret *string) *models.Ne
} }
} }
func (db *Database) UserGetOrCreate(ctx *gin.Context, newUser *models.UserForm) (*models.UserResponse, error) { func (db *Database) UserGetOrCreate(ctx context.Context, newUser *model.UserForm) (*model.UserResponse, error) {
user, err := db.UserGet(ctx, newUser.ID) user, err := db.UserGet(ctx, newUser.ID)
if err != nil { if err != nil {
newUser, err := db.UserCreate(ctx, newUser) newUser, err := db.UserCreate(ctx, newUser)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &models.UserResponse{ID: newUser.ID, Roles: newUser.Roles, Blocked: newUser.Blocked}, nil return &model.UserResponse{ID: newUser.ID, Roles: newUser.Roles, Blocked: newUser.Blocked}, nil
} }
return user, nil return user, nil
} }
func (db *Database) UserCreate(ctx context.Context, newUser *models.UserForm) (*models.NewUserResponse, error) { func (db *Database) UserCreate(ctx context.Context, newUser *model.UserForm) (*model.NewUserResponse, error) {
var key string var key string
var hash *string var hash *string
if newUser.Apikey { if newUser.Apikey {
@@ -92,7 +91,7 @@ func (db *Database) UserCreate(ctx context.Context, newUser *models.UserForm) (*
hash = pointer.String(fmt.Sprintf("%x", sha256.Sum256([]byte(key)))) hash = pointer.String(fmt.Sprintf("%x", sha256.Sum256([]byte(key))))
} }
var doc models.User var doc model.User
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.userCollection.CreateDocument(ctx, newctx, strcase.ToKebab(newUser.ID), toUser(newUser, hash)) meta, err := db.userCollection.CreateDocument(ctx, newctx, strcase.ToKebab(newUser.ID), toUser(newUser, hash))
if err != nil { if err != nil {
@@ -102,8 +101,8 @@ func (db *Database) UserCreate(ctx context.Context, newUser *models.UserForm) (*
return toNewUserResponse(meta.Key, &doc, pointer.String(key)), nil return toNewUserResponse(meta.Key, &doc, pointer.String(key)), nil
} }
func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*models.UserResponse, error) { func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*model.UserResponse, error) {
newUser := &models.UserForm{ newUser := &model.UserForm{
ID: "setup", ID: "setup",
Roles: []string{role.Admin}, Roles: []string{role.Admin},
Apikey: true, Apikey: true,
@@ -111,7 +110,7 @@ func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*mod
} }
hash := pointer.String(fmt.Sprintf("%x", sha256.Sum256([]byte(key)))) hash := pointer.String(fmt.Sprintf("%x", sha256.Sum256([]byte(key))))
var doc models.User var doc model.User
newctx := driver.WithReturnNew(ctx, &doc) newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.userCollection.CreateDocument(ctx, newctx, strcase.ToKebab(newUser.ID), toUser(newUser, hash)) meta, err := db.userCollection.CreateDocument(ctx, newctx, strcase.ToKebab(newUser.ID), toUser(newUser, hash))
if err != nil { if err != nil {
@@ -121,8 +120,8 @@ func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*mod
return toUserResponse(meta.Key, &doc), nil return toUserResponse(meta.Key, &doc), nil
} }
func (db *Database) UserGet(ctx context.Context, id string) (*models.UserResponse, error) { func (db *Database) UserGet(ctx context.Context, id string) (*model.UserResponse, error) {
var doc models.User var doc model.User
meta, err := db.userCollection.ReadDocument(ctx, id, &doc) meta, err := db.userCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -136,16 +135,16 @@ func (db *Database) UserDelete(ctx context.Context, id string) error {
return err return err
} }
func (db *Database) UserList(ctx context.Context) ([]*models.UserResponse, error) { func (db *Database) UserList(ctx context.Context) ([]*model.UserResponse, error) {
query := "FOR d IN @@collection RETURN d" query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserCollectionName}, busdb.ReadOperation) cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserCollectionName}, busdb.ReadOperation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer cursor.Close() defer cursor.Close()
var docs []*models.UserResponse var docs []*model.UserResponse
for { for {
var doc models.User var doc model.User
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) { if driver.IsNoMoreDocuments(err) {
break break
@@ -159,7 +158,7 @@ func (db *Database) UserList(ctx context.Context) ([]*models.UserResponse, error
return docs, err return docs, err
} }
func (db *Database) UserByHash(ctx context.Context, sha256 string) (*models.UserResponse, error) { func (db *Database) UserByHash(ctx context.Context, sha256 string) (*model.UserResponse, error) {
query := `FOR d in @@collection query := `FOR d in @@collection
FILTER d.sha256 == @sha256 FILTER d.sha256 == @sha256
RETURN d` RETURN d`
@@ -170,7 +169,7 @@ func (db *Database) UserByHash(ctx context.Context, sha256 string) (*models.User
} }
defer cursor.Close() defer cursor.Close()
var doc models.User var doc model.User
meta, err := cursor.ReadDocument(ctx, &doc) meta, err := cursor.ReadDocument(ctx, &doc)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -179,8 +178,8 @@ func (db *Database) UserByHash(ctx context.Context, sha256 string) (*models.User
return toUserResponse(meta.Key, &doc), err return toUserResponse(meta.Key, &doc), err
} }
func (db *Database) UserUpdate(ctx context.Context, id string, user *models.UserForm) (*models.UserResponse, error) { func (db *Database) UserUpdate(ctx context.Context, id string, user *model.UserForm) (*model.UserResponse, error) {
var doc models.User var doc model.User
_, err := db.userCollection.ReadDocument(ctx, id, &doc) _, err := db.userCollection.ReadDocument(ctx, id, &doc)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@@ -62,7 +62,7 @@ definitions:
Message: Message:
type: object type: object
properties: properties:
payload: { type: object } payload: { }
secrets: { type: object, additionalProperties: { type: string } } secrets: { type: object, additionalProperties: { type: string } }
context: { $ref: "#/definitions/Context" } context: { $ref: "#/definitions/Context" }

View File

@@ -32,7 +32,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { type: array, items: { $ref: "#/definitions/PlaybookTemplateResponse" } } schema: { $ref: "#/definitions/PlaybookTemplateResponse" }
examples: examples:
test: test:
id: simple-2 id: simple-2

View File

@@ -10,7 +10,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { type: array, items: { $ref: "#/definitions/TaskResponse" } } schema: { type: array, items: { $ref: "#/definitions/TaskWithContext" } }
examples: examples:
test: [ ] test: [ ]
security: [ { roles: [ "ticket:read" ] } ] security: [ { roles: [ "ticket:read" ] } ]

View File

@@ -95,7 +95,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -126,7 +126,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -168,7 +168,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8126 id: 8126
@@ -234,7 +234,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8126 id: 8126
@@ -262,7 +262,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -297,7 +297,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -340,7 +340,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -363,11 +363,11 @@ paths:
operationId: "setSchema" operationId: "setSchema"
parameters: parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8125 } - { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8125 }
- { name: "schema", in: "body", description: "New ticket schema", schema: { type: string }, x-example: "{}" } - { name: "schema", in: "body", description: "New ticket schema", required: true, schema: { type: string }, x-example: "{}" }
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -398,7 +398,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -430,7 +430,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8125 id: 8125
@@ -489,6 +489,7 @@ paths:
order: 2 order: 2
name: Escalate to malware team name: Escalate to malware team
type: task type: task
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/playbooks/{playbookID}: /tickets/{id}/playbooks/{playbookID}:
delete: delete:
@@ -501,7 +502,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -625,7 +626,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -670,7 +671,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -726,7 +727,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -785,7 +786,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -826,7 +827,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123
@@ -882,7 +883,7 @@ paths:
responses: responses:
"200": "200":
description: "successful operation" description: "successful operation"
schema: { $ref: "#/definitions/Artifact" } schema: { $ref: "#/definitions/TicketWithTickets" }
examples: examples:
test: test:
id: 8123 id: 8123

50
file.go
View File

@@ -4,29 +4,29 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log"
"net/http" "net/http"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/gin-gonic/gin" "github.com/go-chi/chi"
tusd "github.com/tus/tusd/pkg/handler" tusd "github.com/tus/tusd/pkg/handler"
"github.com/tus/tusd/pkg/s3store" "github.com/tus/tusd/pkg/s3store"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/storage" "github.com/SecurityBrewery/catalyst/storage"
) )
func upload(client *s3.S3, external string) gin.HandlerFunc { func upload(client *s3.S3, external string) http.HandlerFunc {
return func(ctx *gin.Context) { return func(w http.ResponseWriter, r *http.Request) {
ticketID, exists := ctx.Params.Get("ticketID") ticketID := chi.URLParam(r, "ticketID")
if !exists { if ticketID == "" {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "ticketID not given"}) api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("ticketID not given"))
return return
} }
if err := storage.CreateBucket(client, ticketID); err != nil { if err := storage.CreateBucket(client, ticketID); err != nil {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("could not create bucket: %w", err)}) api.JSONErrorStatus(w, http.StatusBadRequest, fmt.Errorf("could not create bucket: %w", err))
return return
} }
@@ -40,39 +40,38 @@ func upload(client *s3.S3, external string) gin.HandlerFunc {
StoreComposer: composer, StoreComposer: composer,
}) })
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("could not create tusd handler: %w", err)}) api.JSONErrorStatus(w, http.StatusBadRequest, fmt.Errorf("could not create tusd handler: %w", err))
return return
} }
switch ctx.Request.Method { switch r.Method {
case http.MethodHead: case http.MethodHead:
gin.WrapF(handler.HeadFile)(ctx) handler.HeadFile(w, r)
case http.MethodPost: case http.MethodPost:
gin.WrapF(handler.PostFile)(ctx) handler.PostFile(w, r)
case http.MethodPatch: case http.MethodPatch:
gin.WrapF(handler.PatchFile)(ctx) handler.PatchFile(w, r)
default: default:
log.Println(errors.New("unknown method")) api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("unknown method"))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "unknown method"})
} }
} }
} }
func download(downloader *s3manager.Downloader) gin.HandlerFunc { func download(downloader *s3manager.Downloader) http.HandlerFunc {
return func(ctx *gin.Context) { return func(w http.ResponseWriter, r *http.Request) {
ticketID, exists := ctx.Params.Get("ticketID") ticketID := chi.URLParam(r, "ticketID")
if !exists { if ticketID == "" {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "ticketID not given"}) api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("ticketID not given"))
return return
} }
key, exists := ctx.Params.Get("key") key := chi.URLParam(r, "key")
if !exists { if key == "" {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "key not given"}) api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("key not given"))
return return
} }
buf := sequentialWriter{ctx.Writer} buf := sequentialWriter{w}
downloader.Concurrency = 1 downloader.Concurrency = 1
_, err := downloader.Download(buf, &s3.GetObjectInput{ _, err := downloader.Download(buf, &s3.GetObjectInput{
@@ -80,8 +79,7 @@ func download(downloader *s3manager.Downloader) gin.HandlerFunc {
Key: aws.String(key), Key: aws.String(key),
}) })
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err}) api.JSONErrorStatus(w, http.StatusInternalServerError, err)
return
} }
} }
} }

View File

@@ -22,7 +22,8 @@ mv generated/openapi.json generated/catalyst.json
# openapi-generator generate -i generated/community.yml -o generated/python -g python --package-name catalystpy --ignore-file-override .openapi-generator-ignore # openapi-generator generate -i generated/community.yml -o generated/python -g python --package-name catalystpy --ignore-file-override .openapi-generator-ignore
echo generate server and tests echo generate server and tests
go run ./generator/. ./generator # go run ./generator/. ./generator
swachigo generated/community.yml generated
echo generate typescript client echo generate typescript client
openapi-generator generate -i generated/catalyst.yml -o ui/src/client -g typescript-axios --artifact-version 1.0.0-SNAPSHOT openapi-generator generate -i generated/catalyst.yml -o ui/src/client -g typescript-axios --artifact-version 1.0.0-SNAPSHOT

1094
generated/api/api.go Executable file

File diff suppressed because it is too large Load Diff

587
generated/api/test_api.go Executable file

File diff suppressed because one or more lines are too long

View File

@@ -795,10 +795,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"items" : { "$ref" : "#/components/schemas/PlaybookTemplateResponse"
"$ref" : "#/components/schemas/PlaybookTemplateResponse"
},
"type" : "array"
} }
}, },
"test" : { "test" : {
@@ -1245,7 +1242,7 @@
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"items" : { "items" : {
"$ref" : "#/components/schemas/TaskResponse" "$ref" : "#/components/schemas/TaskWithContext"
}, },
"type" : "array" "type" : "array"
} }
@@ -1805,7 +1802,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -1889,7 +1886,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -1976,7 +1973,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2187,7 +2184,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2443,7 +2440,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2660,7 +2657,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/Artifact" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2922,7 +2919,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3013,7 +3010,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3226,7 +3223,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3317,7 +3314,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3418,6 +3415,9 @@
"description" : "successful operation" "description" : "successful operation"
} }
}, },
"security" : [ {
"roles" : [ "ticket:write" ]
} ],
"summary" : "Add a new ticket playbook", "summary" : "Add a new ticket playbook",
"tags" : [ "tickets" ], "tags" : [ "tickets" ],
"x-codegen-request-body-name" : "playbook" "x-codegen-request-body-name" : "playbook"
@@ -3451,7 +3451,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3545,7 +3545,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3776,7 +3776,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -4038,7 +4038,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -4112,14 +4112,14 @@
} }
}, },
"description" : "New ticket schema", "description" : "New ticket schema",
"required" : false "required" : true
}, },
"responses" : { "responses" : {
"200" : { "200" : {
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -4207,7 +4207,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -4273,7 +4273,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -5433,7 +5433,6 @@
"$ref" : "#/components/schemas/Context" "$ref" : "#/components/schemas/Context"
}, },
"payload" : { "payload" : {
"properties" : { },
"type" : "object" "type" : "object"
}, },
"secrets" : { "secrets" : {

View File

@@ -325,8 +325,7 @@ definitions:
properties: properties:
context: context:
$ref: '#/definitions/Context' $ref: '#/definitions/Context'
payload: payload: {}
type: object
secrets: secrets:
additionalProperties: additionalProperties:
type: string type: string
@@ -2251,9 +2250,7 @@ paths:
name: Escalate to malware team name: Escalate to malware team
type: task type: task
schema: schema:
items: $ref: '#/definitions/PlaybookTemplateResponse'
$ref: '#/definitions/PlaybookTemplateResponse'
type: array
security: security:
- roles: - roles:
- playbook:write - playbook:write
@@ -2687,7 +2684,7 @@ paths:
test: [] test: []
schema: schema:
items: items:
$ref: '#/definitions/TaskResponse' $ref: '#/definitions/TaskWithContext'
type: array type: array
security: security:
- roles: - roles:
@@ -3726,7 +3723,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:read - ticket:read
@@ -3801,7 +3798,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4053,7 +4050,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4297,7 +4294,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4580,7 +4577,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4841,7 +4838,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/Artifact' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4938,7 +4935,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5186,7 +5183,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5257,7 +5254,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5388,7 +5385,10 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security:
- roles:
- ticket:write
summary: Add a new ticket playbook summary: Add a new ticket playbook
tags: tags:
- tickets - tickets
@@ -5527,7 +5527,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5809,7 +5809,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -6073,7 +6073,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -6167,7 +6167,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -6188,6 +6188,7 @@ paths:
- description: New ticket schema - description: New ticket schema
in: body in: body
name: schema name: schema
required: true
schema: schema:
type: string type: string
x-example: '{}' x-example: '{}'
@@ -6228,7 +6229,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -6275,7 +6276,7 @@ paths:
status: closed status: closed
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -6540,7 +6541,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write

View File

@@ -563,10 +563,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"items" : { "$ref" : "#/components/schemas/PlaybookTemplateResponse"
"$ref" : "#/components/schemas/PlaybookTemplateResponse"
},
"type" : "array"
} }
}, },
"test" : { "test" : {
@@ -815,7 +812,7 @@
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"items" : { "items" : {
"$ref" : "#/components/schemas/TaskResponse" "$ref" : "#/components/schemas/TaskWithContext"
}, },
"type" : "array" "type" : "array"
} }
@@ -1375,7 +1372,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -1459,7 +1456,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -1546,7 +1543,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -1757,7 +1754,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2013,7 +2010,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2230,7 +2227,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/Artifact" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2492,7 +2489,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2583,7 +2580,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2796,7 +2793,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2887,7 +2884,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -2988,6 +2985,9 @@
"description" : "successful operation" "description" : "successful operation"
} }
}, },
"security" : [ {
"roles" : [ "ticket:write" ]
} ],
"summary" : "Add a new ticket playbook", "summary" : "Add a new ticket playbook",
"tags" : [ "tickets" ], "tags" : [ "tickets" ],
"x-codegen-request-body-name" : "playbook" "x-codegen-request-body-name" : "playbook"
@@ -3021,7 +3021,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3115,7 +3115,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3346,7 +3346,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3608,7 +3608,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3682,14 +3682,14 @@
} }
}, },
"description" : "New ticket schema", "description" : "New ticket schema",
"required" : false "required" : true
}, },
"responses" : { "responses" : {
"200" : { "200" : {
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3777,7 +3777,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -3843,7 +3843,7 @@
"content" : { "content" : {
"application/json" : { "application/json" : {
"schema" : { "schema" : {
"$ref" : "#/components/schemas/TicketResponse" "$ref" : "#/components/schemas/TicketWithTickets"
} }
}, },
"test" : { "test" : {
@@ -4920,7 +4920,6 @@
"$ref" : "#/components/schemas/Context" "$ref" : "#/components/schemas/Context"
}, },
"payload" : { "payload" : {
"properties" : { },
"type" : "object" "type" : "object"
}, },
"secrets" : { "secrets" : {

View File

@@ -260,8 +260,7 @@ definitions:
properties: properties:
context: context:
$ref: '#/definitions/Context' $ref: '#/definitions/Context'
payload: payload: {}
type: object
secrets: secrets:
additionalProperties: additionalProperties:
type: string type: string
@@ -1980,9 +1979,7 @@ paths:
name: Escalate to malware team name: Escalate to malware team
type: task type: task
schema: schema:
items: $ref: '#/definitions/PlaybookTemplateResponse'
$ref: '#/definitions/PlaybookTemplateResponse'
type: array
security: security:
- roles: - roles:
- playbook:write - playbook:write
@@ -2275,7 +2272,7 @@ paths:
test: [] test: []
schema: schema:
items: items:
$ref: '#/definitions/TaskResponse' $ref: '#/definitions/TaskWithContext'
type: array type: array
security: security:
- roles: - roles:
@@ -3314,7 +3311,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:read - ticket:read
@@ -3389,7 +3386,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -3641,7 +3638,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -3885,7 +3882,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4168,7 +4165,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4429,7 +4426,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/Artifact' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4526,7 +4523,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4774,7 +4771,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4845,7 +4842,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -4976,7 +4973,10 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security:
- roles:
- ticket:write
summary: Add a new ticket playbook summary: Add a new ticket playbook
tags: tags:
- tickets - tickets
@@ -5115,7 +5115,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5397,7 +5397,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5661,7 +5661,7 @@ paths:
status: closed status: closed
type: incident type: incident
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5755,7 +5755,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5776,6 +5776,7 @@ paths:
- description: New ticket schema - description: New ticket schema
in: body in: body
name: schema name: schema
required: true
schema: schema:
type: string type: string
x-example: '{}' x-example: '{}'
@@ -5816,7 +5817,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -5863,7 +5864,7 @@ paths:
status: closed status: closed
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write
@@ -6128,7 +6129,7 @@ paths:
type: alert type: alert
type: alert type: alert
schema: schema:
$ref: '#/definitions/TicketResponse' $ref: '#/definitions/TicketWithTickets'
security: security:
- roles: - roles:
- ticket:write - ticket:write

View File

@@ -1,4 +1,4 @@
package models package model
import ( import (
"fmt" "fmt"
@@ -78,7 +78,7 @@ func init() {
gojsonschema.NewStringLoader(`{"type":"object","required":["automation"],"x-embed":"","properties":{"automation":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"payload":{}},"$id":"#/definitions/JobForm"}`), gojsonschema.NewStringLoader(`{"type":"object","required":["automation"],"x-embed":"","properties":{"automation":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"payload":{}},"$id":"#/definitions/JobForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","automation","status"],"x-embed":"","properties":{"automation":{"type":"string"},"container":{"type":"string"},"id":{"type":"string"},"log":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"output":{"type":"object"},"payload":{},"status":{"type":"string"}},"$id":"#/definitions/JobResponse"}`), gojsonschema.NewStringLoader(`{"type":"object","required":["id","automation","status"],"x-embed":"","properties":{"automation":{"type":"string"},"container":{"type":"string"},"id":{"type":"string"},"log":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"output":{"type":"object"},"payload":{},"status":{"type":"string"}},"$id":"#/definitions/JobResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["type","reference","creator","created","message"],"x-embed":"","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"},"reference":{"type":"string"},"type":{"type":"string"}},"$id":"#/definitions/LogEntry"}`), gojsonschema.NewStringLoader(`{"type":"object","required":["type","reference","creator","created","message"],"x-embed":"","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"},"reference":{"type":"string"},"type":{"type":"string"}},"$id":"#/definitions/LogEntry"}`),
gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"context":{"$ref":"#/definitions/Context"},"payload":{"type":"object"},"secrets":{"type":"object","additionalProperties":{"type":"string"}}},"$id":"#/definitions/Message"}`), gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"context":{"$ref":"#/definitions/Context"},"payload":{},"secrets":{"type":"object","additionalProperties":{"type":"string"}}},"$id":"#/definitions/Message"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","blocked","roles"],"x-embed":"","properties":{"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"},"secret":{"type":"string"}},"$id":"#/definitions/NewUserResponse"}`), gojsonschema.NewStringLoader(`{"type":"object","required":["id","blocked","roles"],"x-embed":"","properties":{"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"},"secret":{"type":"string"}},"$id":"#/definitions/NewUserResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"artifact_origin":{"$ref":"#/definitions/ArtifactOrigin"},"task_origin":{"$ref":"#/definitions/TaskOrigin"}},"$id":"#/definitions/Origin"}`), gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"artifact_origin":{"$ref":"#/definitions/ArtifactOrigin"},"task_origin":{"$ref":"#/definitions/TaskOrigin"}},"$id":"#/definitions/Origin"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","tasks"],"x-embed":"","properties":{"name":{"type":"string"},"tasks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Task"}}},"$id":"#/definitions/Playbook"}`), gojsonschema.NewStringLoader(`{"type":"object","required":["name","tasks"],"x-embed":"","properties":{"name":{"type":"string"},"tasks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Task"}}},"$id":"#/definitions/Playbook"}`),
@@ -223,14 +223,14 @@ type Context struct {
} }
type Enrichment struct { type Enrichment struct {
Created time.Time `json:"created"` Created time.Time `json:"created"`
Data interface{} `json:"data"` Data map[string]interface{} `json:"data"`
Name string `json:"name"` Name string `json:"name"`
} }
type EnrichmentForm struct { type EnrichmentForm struct {
Data interface{} `json:"data"` Data map[string]interface{} `json:"data"`
Name string `json:"name"` Name string `json:"name"`
} }
type File struct { type File struct {
@@ -239,14 +239,14 @@ type File struct {
} }
type Job struct { type Job struct {
Automation string `json:"automation"` Automation string `json:"automation"`
Container *string `json:"container,omitempty"` Container *string `json:"container,omitempty"`
Log *string `json:"log,omitempty"` Log *string `json:"log,omitempty"`
Origin *Origin `json:"origin,omitempty"` Origin *Origin `json:"origin,omitempty"`
Output interface{} `json:"output,omitempty"` Output map[string]interface{} `json:"output,omitempty"`
Payload interface{} `json:"payload,omitempty"` Payload interface{} `json:"payload,omitempty"`
Running bool `json:"running"` Running bool `json:"running"`
Status string `json:"status"` Status string `json:"status"`
} }
type JobForm struct { type JobForm struct {
@@ -256,14 +256,14 @@ type JobForm struct {
} }
type JobResponse struct { type JobResponse struct {
Automation string `json:"automation"` Automation string `json:"automation"`
Container *string `json:"container,omitempty"` Container *string `json:"container,omitempty"`
ID string `json:"id"` ID string `json:"id"`
Log *string `json:"log,omitempty"` Log *string `json:"log,omitempty"`
Origin *Origin `json:"origin,omitempty"` Origin *Origin `json:"origin,omitempty"`
Output interface{} `json:"output,omitempty"` Output map[string]interface{} `json:"output,omitempty"`
Payload interface{} `json:"payload,omitempty"` Payload interface{} `json:"payload,omitempty"`
Status string `json:"status"` Status string `json:"status"`
} }
type LogEntry struct { type LogEntry struct {
@@ -340,33 +340,33 @@ type Statistics struct {
} }
type Task struct { type Task struct {
Automation *string `json:"automation,omitempty"` Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"` Closed *time.Time `json:"closed,omitempty"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
Data interface{} `json:"data,omitempty"` Data map[string]interface{} `json:"data,omitempty"`
Done bool `json:"done"` Done bool `json:"done"`
Join *bool `json:"join,omitempty"` Join *bool `json:"join,omitempty"`
Name string `json:"name"` Name string `json:"name"`
Next map[string]string `json:"next,omitempty"` Next map[string]string `json:"next,omitempty"`
Owner *string `json:"owner,omitempty"` Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"` Payload map[string]string `json:"payload,omitempty"`
Schema interface{} `json:"schema,omitempty"` Schema map[string]interface{} `json:"schema,omitempty"`
Type string `json:"type"` Type string `json:"type"`
} }
type TaskForm struct { type TaskForm struct {
Automation *string `json:"automation,omitempty"` Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"` Closed *time.Time `json:"closed,omitempty"`
Created *time.Time `json:"created,omitempty"` Created *time.Time `json:"created,omitempty"`
Data interface{} `json:"data,omitempty"` Data map[string]interface{} `json:"data,omitempty"`
Done *bool `json:"done,omitempty"` Done *bool `json:"done,omitempty"`
Join *bool `json:"join,omitempty"` Join *bool `json:"join,omitempty"`
Name string `json:"name"` Name string `json:"name"`
Next map[string]string `json:"next,omitempty"` Next map[string]string `json:"next,omitempty"`
Owner *string `json:"owner,omitempty"` Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"` Payload map[string]string `json:"payload,omitempty"`
Schema interface{} `json:"schema,omitempty"` Schema map[string]interface{} `json:"schema,omitempty"`
Type string `json:"type"` Type string `json:"type"`
} }
type TaskOrigin struct { type TaskOrigin struct {
@@ -376,54 +376,54 @@ type TaskOrigin struct {
} }
type TaskResponse struct { type TaskResponse struct {
Active bool `json:"active"` Active bool `json:"active"`
Automation *string `json:"automation,omitempty"` Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"` Closed *time.Time `json:"closed,omitempty"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
Data interface{} `json:"data,omitempty"` Data map[string]interface{} `json:"data,omitempty"`
Done bool `json:"done"` Done bool `json:"done"`
Join *bool `json:"join,omitempty"` Join *bool `json:"join,omitempty"`
Name string `json:"name"` Name string `json:"name"`
Next map[string]string `json:"next,omitempty"` Next map[string]string `json:"next,omitempty"`
Order int64 `json:"order"` Order int64 `json:"order"`
Owner *string `json:"owner,omitempty"` Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"` Payload map[string]string `json:"payload,omitempty"`
Schema interface{} `json:"schema,omitempty"` Schema map[string]interface{} `json:"schema,omitempty"`
Type string `json:"type"` Type string `json:"type"`
} }
type TaskWithContext struct { type TaskWithContext struct {
PlaybookId string `json:"playbook_id"` PlaybookId string `json:"playbook_id"`
PlaybookName string `json:"playbook_name"` PlaybookName string `json:"playbook_name"`
Task TaskResponse `json:"task"` Task *TaskResponse `json:"task"`
TaskId string `json:"task_id"` TaskId string `json:"task_id"`
TicketId int64 `json:"ticket_id"` TicketId int64 `json:"ticket_id"`
TicketName string `json:"ticket_name"` TicketName string `json:"ticket_name"`
} }
type Ticket struct { type Ticket struct {
Artifacts []*Artifact `json:"artifacts,omitempty"` Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"` Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"` Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"` Files []*File `json:"files,omitempty"`
Modified time.Time `json:"modified"` Modified time.Time `json:"modified"`
Name string `json:"name"` Name string `json:"name"`
Owner *string `json:"owner,omitempty"` Owner *string `json:"owner,omitempty"`
Playbooks map[string]*Playbook `json:"playbooks,omitempty"` Playbooks map[string]*Playbook `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"` Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"` References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"` Schema string `json:"schema"`
Status string `json:"status"` Status string `json:"status"`
Type string `json:"type"` Type string `json:"type"`
Write []string `json:"write,omitempty"` Write []string `json:"write,omitempty"`
} }
type TicketForm struct { type TicketForm struct {
Artifacts []*Artifact `json:"artifacts,omitempty"` Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"` Comments []*Comment `json:"comments,omitempty"`
Created *time.Time `json:"created,omitempty"` Created *time.Time `json:"created,omitempty"`
Details interface{} `json:"details,omitempty"` Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"` Files []*File `json:"files,omitempty"`
ID *int64 `json:"id,omitempty"` ID *int64 `json:"id,omitempty"`
Modified *time.Time `json:"modified,omitempty"` Modified *time.Time `json:"modified,omitempty"`
@@ -447,7 +447,7 @@ type TicketResponse struct {
Artifacts []*Artifact `json:"artifacts,omitempty"` Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"` Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"` Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"` Files []*File `json:"files,omitempty"`
ID int64 `json:"id"` ID int64 `json:"id"`
Modified time.Time `json:"modified"` Modified time.Time `json:"modified"`
@@ -463,22 +463,22 @@ type TicketResponse struct {
} }
type TicketSimpleResponse struct { type TicketSimpleResponse struct {
Artifacts []*Artifact `json:"artifacts,omitempty"` Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"` Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"` Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"` Files []*File `json:"files,omitempty"`
ID int64 `json:"id"` ID int64 `json:"id"`
Modified time.Time `json:"modified"` Modified time.Time `json:"modified"`
Name string `json:"name"` Name string `json:"name"`
Owner *string `json:"owner,omitempty"` Owner *string `json:"owner,omitempty"`
Playbooks map[string]*Playbook `json:"playbooks,omitempty"` Playbooks map[string]*Playbook `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"` Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"` References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"` Schema string `json:"schema"`
Status string `json:"status"` Status string `json:"status"`
Type string `json:"type"` Type string `json:"type"`
Write []string `json:"write,omitempty"` Write []string `json:"write,omitempty"`
} }
type TicketTemplate struct { type TicketTemplate struct {
@@ -528,7 +528,7 @@ type TicketWithTickets struct {
Artifacts []*Artifact `json:"artifacts,omitempty"` Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"` Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"` Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"` Files []*File `json:"files,omitempty"`
ID int64 `json:"id"` ID int64 `json:"id"`
Logs []*LogEntry `json:"logs,omitempty"` Logs []*LogEntry `json:"logs,omitempty"`

View File

@@ -1,252 +0,0 @@
package restapi
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/automations"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/jobs"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/logs"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/playbooks"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/settings"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/statistics"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/tasks"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/templates"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/tickets"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/tickettypes"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/userdata"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/users"
"github.com/SecurityBrewery/catalyst/role"
)
// Service is the interface that must be implemented in order to provide
// business logic for the Server service.
type Service interface {
AddArtifact(ctx context.Context, params *tickets.AddArtifactParams) *api.Response
AddComment(ctx context.Context, params *tickets.AddCommentParams) *api.Response
AddTicketPlaybook(ctx context.Context, params *tickets.AddTicketPlaybookParams) *api.Response
CompleteTask(ctx context.Context, params *tickets.CompleteTaskParams) *api.Response
CreateAutomation(ctx context.Context, params *automations.CreateAutomationParams) *api.Response
CreatePlaybook(ctx context.Context, params *playbooks.CreatePlaybookParams) *api.Response
CreateTemplate(ctx context.Context, params *templates.CreateTemplateParams) *api.Response
CreateTicket(ctx context.Context, params *tickets.CreateTicketParams) *api.Response
CreateTicketBatch(ctx context.Context, params *tickets.CreateTicketBatchParams) *api.Response
CreateTicketType(ctx context.Context, params *tickettypes.CreateTicketTypeParams) *api.Response
CreateUser(ctx context.Context, params *users.CreateUserParams) *api.Response
CurrentUser(ctx context.Context) *api.Response
CurrentUserData(ctx context.Context) *api.Response
DeleteAutomation(ctx context.Context, params *automations.DeleteAutomationParams) *api.Response
DeletePlaybook(ctx context.Context, params *playbooks.DeletePlaybookParams) *api.Response
DeleteTemplate(ctx context.Context, params *templates.DeleteTemplateParams) *api.Response
DeleteTicket(ctx context.Context, params *tickets.DeleteTicketParams) *api.Response
DeleteTicketType(ctx context.Context, params *tickettypes.DeleteTicketTypeParams) *api.Response
DeleteUser(ctx context.Context, params *users.DeleteUserParams) *api.Response
EnrichArtifact(ctx context.Context, params *tickets.EnrichArtifactParams) *api.Response
GetArtifact(ctx context.Context, params *tickets.GetArtifactParams) *api.Response
GetAutomation(ctx context.Context, params *automations.GetAutomationParams) *api.Response
GetJob(ctx context.Context, params *jobs.GetJobParams) *api.Response
GetLogs(ctx context.Context, params *logs.GetLogsParams) *api.Response
GetPlaybook(ctx context.Context, params *playbooks.GetPlaybookParams) *api.Response
GetSettings(ctx context.Context) *api.Response
GetStatistics(ctx context.Context) *api.Response
GetTemplate(ctx context.Context, params *templates.GetTemplateParams) *api.Response
GetTicket(ctx context.Context, params *tickets.GetTicketParams) *api.Response
GetTicketType(ctx context.Context, params *tickettypes.GetTicketTypeParams) *api.Response
GetUser(ctx context.Context, params *users.GetUserParams) *api.Response
GetUserData(ctx context.Context, params *userdata.GetUserDataParams) *api.Response
LinkFiles(ctx context.Context, params *tickets.LinkFilesParams) *api.Response
LinkTicket(ctx context.Context, params *tickets.LinkTicketParams) *api.Response
ListAutomations(ctx context.Context) *api.Response
ListJobs(ctx context.Context) *api.Response
ListPlaybooks(ctx context.Context) *api.Response
ListTasks(ctx context.Context) *api.Response
ListTemplates(ctx context.Context) *api.Response
ListTicketTypes(ctx context.Context) *api.Response
ListTickets(ctx context.Context, params *tickets.ListTicketsParams) *api.Response
ListUserData(ctx context.Context) *api.Response
ListUsers(ctx context.Context) *api.Response
RemoveArtifact(ctx context.Context, params *tickets.RemoveArtifactParams) *api.Response
RemoveComment(ctx context.Context, params *tickets.RemoveCommentParams) *api.Response
RemoveTicketPlaybook(ctx context.Context, params *tickets.RemoveTicketPlaybookParams) *api.Response
RunArtifact(ctx context.Context, params *tickets.RunArtifactParams) *api.Response
RunJob(ctx context.Context, params *jobs.RunJobParams) *api.Response
RunTask(ctx context.Context, params *tickets.RunTaskParams) *api.Response
SetArtifact(ctx context.Context, params *tickets.SetArtifactParams) *api.Response
SetReferences(ctx context.Context, params *tickets.SetReferencesParams) *api.Response
SetSchema(ctx context.Context, params *tickets.SetSchemaParams) *api.Response
SetTask(ctx context.Context, params *tickets.SetTaskParams) *api.Response
UnlinkTicket(ctx context.Context, params *tickets.UnlinkTicketParams) *api.Response
UpdateAutomation(ctx context.Context, params *automations.UpdateAutomationParams) *api.Response
UpdateCurrentUserData(ctx context.Context, params *userdata.UpdateCurrentUserDataParams) *api.Response
UpdateJob(ctx context.Context, params *jobs.UpdateJobParams) *api.Response
UpdatePlaybook(ctx context.Context, params *playbooks.UpdatePlaybookParams) *api.Response
UpdateTemplate(ctx context.Context, params *templates.UpdateTemplateParams) *api.Response
UpdateTicket(ctx context.Context, params *tickets.UpdateTicketParams) *api.Response
UpdateTicketType(ctx context.Context, params *tickettypes.UpdateTicketTypeParams) *api.Response
UpdateUser(ctx context.Context, params *users.UpdateUserParams) *api.Response
UpdateUserData(ctx context.Context, params *userdata.UpdateUserDataParams) *api.Response
}
// Config defines the config options for the API server.
type Config struct {
Address string
InsecureHTTP bool
TLSCertFile string
TLSKeyFile string
}
// Server defines the Server service.
type Server struct {
*gin.Engine
config *Config
server *http.Server
service Service
ApiGroup *gin.RouterGroup
RoleAuth func([]role.Role) gin.HandlerFunc
}
// New initializes a new Server service.
func New(svc Service, config *Config) *Server {
engine := gin.New()
engine.Use(gin.Recovery())
return &Server{
Engine: engine,
service: svc,
config: config,
server: &http.Server{
Addr: config.Address,
Handler: engine,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
},
ApiGroup: engine.Group("/api"),
RoleAuth: func(i []role.Role) gin.HandlerFunc { return func(c *gin.Context) { c.Next() } },
}
}
// ConfigureRoutes configures the routes for the Server service.
// Configuring of routes includes setting up Auth if it is enabled.
func (s *Server) ConfigureRoutes() {
s.ApiGroup.POST("/tickets/:id/artifacts", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.AddArtifactEndpoint(s.service.AddArtifact))
s.ApiGroup.POST("/tickets/:id/comments", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.AddCommentEndpoint(s.service.AddComment))
s.ApiGroup.POST("/tickets/:id/playbooks", s.RoleAuth([]role.Role{}), tickets.AddTicketPlaybookEndpoint(s.service.AddTicketPlaybook))
s.ApiGroup.PUT("/tickets/:id/playbooks/:playbookID/task/:taskID/complete", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.CompleteTaskEndpoint(s.service.CompleteTask))
s.ApiGroup.POST("/automations", s.RoleAuth([]role.Role{role.AutomationWrite}), automations.CreateAutomationEndpoint(s.service.CreateAutomation))
s.ApiGroup.POST("/playbooks", s.RoleAuth([]role.Role{role.PlaybookWrite}), playbooks.CreatePlaybookEndpoint(s.service.CreatePlaybook))
s.ApiGroup.POST("/templates", s.RoleAuth([]role.Role{role.TemplateWrite}), templates.CreateTemplateEndpoint(s.service.CreateTemplate))
s.ApiGroup.POST("/tickets", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.CreateTicketEndpoint(s.service.CreateTicket))
s.ApiGroup.POST("/tickets/batch", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.CreateTicketBatchEndpoint(s.service.CreateTicketBatch))
s.ApiGroup.POST("/tickettypes", s.RoleAuth([]role.Role{role.TickettypeWrite}), tickettypes.CreateTicketTypeEndpoint(s.service.CreateTicketType))
s.ApiGroup.POST("/users", s.RoleAuth([]role.Role{role.UserWrite}), users.CreateUserEndpoint(s.service.CreateUser))
s.ApiGroup.GET("/currentuser", s.RoleAuth([]role.Role{role.CurrentuserRead}), users.CurrentUserEndpoint(s.service.CurrentUser))
s.ApiGroup.GET("/currentuserdata", s.RoleAuth([]role.Role{role.CurrentuserdataRead}), userdata.CurrentUserDataEndpoint(s.service.CurrentUserData))
s.ApiGroup.DELETE("/automations/:id", s.RoleAuth([]role.Role{role.AutomationWrite}), automations.DeleteAutomationEndpoint(s.service.DeleteAutomation))
s.ApiGroup.DELETE("/playbooks/:id", s.RoleAuth([]role.Role{role.PlaybookWrite}), playbooks.DeletePlaybookEndpoint(s.service.DeletePlaybook))
s.ApiGroup.DELETE("/templates/:id", s.RoleAuth([]role.Role{role.TemplateWrite}), templates.DeleteTemplateEndpoint(s.service.DeleteTemplate))
s.ApiGroup.DELETE("/tickets/:id", s.RoleAuth([]role.Role{role.TicketDelete}), tickets.DeleteTicketEndpoint(s.service.DeleteTicket))
s.ApiGroup.DELETE("/tickettypes/:id", s.RoleAuth([]role.Role{role.TickettypeWrite}), tickettypes.DeleteTicketTypeEndpoint(s.service.DeleteTicketType))
s.ApiGroup.DELETE("/users/:id", s.RoleAuth([]role.Role{role.UserWrite}), users.DeleteUserEndpoint(s.service.DeleteUser))
s.ApiGroup.POST("/tickets/:id/artifacts/:name/enrich", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.EnrichArtifactEndpoint(s.service.EnrichArtifact))
s.ApiGroup.GET("/tickets/:id/artifacts/:name", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.GetArtifactEndpoint(s.service.GetArtifact))
s.ApiGroup.GET("/automations/:id", s.RoleAuth([]role.Role{role.AutomationRead}), automations.GetAutomationEndpoint(s.service.GetAutomation))
s.ApiGroup.GET("/jobs/:id", s.RoleAuth([]role.Role{role.JobRead}), jobs.GetJobEndpoint(s.service.GetJob))
s.ApiGroup.GET("/logs/:reference", s.RoleAuth([]role.Role{role.LogRead}), logs.GetLogsEndpoint(s.service.GetLogs))
s.ApiGroup.GET("/playbooks/:id", s.RoleAuth([]role.Role{role.PlaybookRead}), playbooks.GetPlaybookEndpoint(s.service.GetPlaybook))
s.ApiGroup.GET("/settings", s.RoleAuth([]role.Role{role.SettingsRead}), settings.GetSettingsEndpoint(s.service.GetSettings))
s.ApiGroup.GET("/statistics", s.RoleAuth([]role.Role{role.TicketRead}), statistics.GetStatisticsEndpoint(s.service.GetStatistics))
s.ApiGroup.GET("/templates/:id", s.RoleAuth([]role.Role{role.TemplateRead}), templates.GetTemplateEndpoint(s.service.GetTemplate))
s.ApiGroup.GET("/tickets/:id", s.RoleAuth([]role.Role{role.TicketRead}), tickets.GetTicketEndpoint(s.service.GetTicket))
s.ApiGroup.GET("/tickettypes/:id", s.RoleAuth([]role.Role{role.TickettypeRead}), tickettypes.GetTicketTypeEndpoint(s.service.GetTicketType))
s.ApiGroup.GET("/users/:id", s.RoleAuth([]role.Role{role.UserRead}), users.GetUserEndpoint(s.service.GetUser))
s.ApiGroup.GET("/userdata/:id", s.RoleAuth([]role.Role{role.UserdataRead}), userdata.GetUserDataEndpoint(s.service.GetUserData))
s.ApiGroup.PUT("/tickets/:id/files", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.LinkFilesEndpoint(s.service.LinkFiles))
s.ApiGroup.PATCH("/tickets/:id/tickets", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.LinkTicketEndpoint(s.service.LinkTicket))
s.ApiGroup.GET("/automations", s.RoleAuth([]role.Role{role.AutomationRead}), automations.ListAutomationsEndpoint(s.service.ListAutomations))
s.ApiGroup.GET("/jobs", s.RoleAuth([]role.Role{role.JobRead}), jobs.ListJobsEndpoint(s.service.ListJobs))
s.ApiGroup.GET("/playbooks", s.RoleAuth([]role.Role{role.PlaybookRead}), playbooks.ListPlaybooksEndpoint(s.service.ListPlaybooks))
s.ApiGroup.GET("/tasks", s.RoleAuth([]role.Role{role.TicketRead}), tasks.ListTasksEndpoint(s.service.ListTasks))
s.ApiGroup.GET("/templates", s.RoleAuth([]role.Role{role.TemplateRead}), templates.ListTemplatesEndpoint(s.service.ListTemplates))
s.ApiGroup.GET("/tickettypes", s.RoleAuth([]role.Role{role.TickettypeRead}), tickettypes.ListTicketTypesEndpoint(s.service.ListTicketTypes))
s.ApiGroup.GET("/tickets", s.RoleAuth([]role.Role{role.TicketRead}), tickets.ListTicketsEndpoint(s.service.ListTickets))
s.ApiGroup.GET("/userdata", s.RoleAuth([]role.Role{role.UserdataRead}), userdata.ListUserDataEndpoint(s.service.ListUserData))
s.ApiGroup.GET("/users", s.RoleAuth([]role.Role{role.UserRead}), users.ListUsersEndpoint(s.service.ListUsers))
s.ApiGroup.DELETE("/tickets/:id/artifacts/:name", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RemoveArtifactEndpoint(s.service.RemoveArtifact))
s.ApiGroup.DELETE("/tickets/:id/comments/:commentID", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RemoveCommentEndpoint(s.service.RemoveComment))
s.ApiGroup.DELETE("/tickets/:id/playbooks/:playbookID", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RemoveTicketPlaybookEndpoint(s.service.RemoveTicketPlaybook))
s.ApiGroup.POST("/tickets/:id/artifacts/:name/run/:automation", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RunArtifactEndpoint(s.service.RunArtifact))
s.ApiGroup.POST("/jobs", s.RoleAuth([]role.Role{role.JobWrite}), jobs.RunJobEndpoint(s.service.RunJob))
s.ApiGroup.POST("/tickets/:id/playbooks/:playbookID/task/:taskID/run", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RunTaskEndpoint(s.service.RunTask))
s.ApiGroup.PUT("/tickets/:id/artifacts/:name", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetArtifactEndpoint(s.service.SetArtifact))
s.ApiGroup.PUT("/tickets/:id/references", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetReferencesEndpoint(s.service.SetReferences))
s.ApiGroup.PUT("/tickets/:id/schema", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetSchemaEndpoint(s.service.SetSchema))
s.ApiGroup.PUT("/tickets/:id/playbooks/:playbookID/task/:taskID", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetTaskEndpoint(s.service.SetTask))
s.ApiGroup.DELETE("/tickets/:id/tickets", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.UnlinkTicketEndpoint(s.service.UnlinkTicket))
s.ApiGroup.PUT("/automations/:id", s.RoleAuth([]role.Role{role.AutomationWrite}), automations.UpdateAutomationEndpoint(s.service.UpdateAutomation))
s.ApiGroup.PUT("/currentuserdata", s.RoleAuth([]role.Role{role.CurrentuserdataWrite}), userdata.UpdateCurrentUserDataEndpoint(s.service.UpdateCurrentUserData))
s.ApiGroup.PUT("/jobs/:id", s.RoleAuth([]role.Role{role.JobWrite}), jobs.UpdateJobEndpoint(s.service.UpdateJob))
s.ApiGroup.PUT("/playbooks/:id", s.RoleAuth([]role.Role{role.PlaybookWrite}), playbooks.UpdatePlaybookEndpoint(s.service.UpdatePlaybook))
s.ApiGroup.PUT("/templates/:id", s.RoleAuth([]role.Role{role.TemplateWrite}), templates.UpdateTemplateEndpoint(s.service.UpdateTemplate))
s.ApiGroup.PUT("/tickets/:id", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.UpdateTicketEndpoint(s.service.UpdateTicket))
s.ApiGroup.PUT("/tickettypes/:id", s.RoleAuth([]role.Role{role.TickettypeWrite}), tickettypes.UpdateTicketTypeEndpoint(s.service.UpdateTicketType))
s.ApiGroup.PUT("/users/:id", s.RoleAuth([]role.Role{role.UserWrite}), users.UpdateUserEndpoint(s.service.UpdateUser))
s.ApiGroup.PUT("/userdata/:id", s.RoleAuth([]role.Role{role.UserdataWrite}), userdata.UpdateUserDataEndpoint(s.service.UpdateUserData))
}
// run the Server. It will listen on either HTTP or HTTPS depending on the
// config passed to NewServer.
func (s *Server) run() error {
log.Printf("Serving on address %s\n", s.server.Addr)
if s.config.InsecureHTTP {
return s.server.ListenAndServe()
}
return s.server.ListenAndServeTLS(s.config.TLSCertFile, s.config.TLSKeyFile)
}
// Shutdown will gracefully shutdown the Server.
func (s *Server) Shutdown() error {
return s.server.Shutdown(context.Background())
}
// RunWithSigHandler runs the Server with SIGTERM handling automatically
// enabled. The server will listen for a SIGTERM signal and gracefully shutdown
// the web server.
// It's possible to optionally pass any number shutdown functions which will
// execute one by one after the webserver has been shutdown successfully.
func (s *Server) RunWithSigHandler(shutdown ...func() error) error {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigCh
s.Shutdown()
}()
err := s.run()
if err != nil {
if err != http.ErrServerClosed {
return err
}
}
for _, fn := range shutdown {
err := fn()
if err != nil {
return err
}
}
return nil
}

View File

@@ -1,6 +0,0 @@
package api
type Response struct {
Code int
Body interface{}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,90 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreateAutomationEndpoint executes the core logic of the related
// route endpoint.
func CreateAutomationEndpoint(handler func(ctx context.Context, params *CreateAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreateAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreateAutomationParams creates a new CreateAutomationParams object
// with the default values initialized.
func NewCreateAutomationParams() *CreateAutomationParams {
var ()
return &CreateAutomationParams{}
}
// CreateAutomationParams contains all the bound params for the create automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters createAutomation
type CreateAutomationParams struct {
/*New automation
Required: true
In: body
*/
Automation *models.AutomationForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreateAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.AutomationForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("automation", "body", ""))
} else {
res = append(res, errors.NewParseError("automation", "body", "", err))
}
} else {
o.Automation = &body
}
} else {
res = append(res, errors.Required("automation", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,87 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeleteAutomationEndpoint executes the core logic of the related
// route endpoint.
func DeleteAutomationEndpoint(handler func(ctx context.Context, params *DeleteAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeleteAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeleteAutomationParams creates a new DeleteAutomationParams object
// with the default values initialized.
func NewDeleteAutomationParams() *DeleteAutomationParams {
var ()
return &DeleteAutomationParams{}
}
// DeleteAutomationParams contains all the bound params for the delete automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters deleteAutomation
type DeleteAutomationParams struct {
/*Automation ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeleteAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeleteAutomationParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetAutomationEndpoint executes the core logic of the related
// route endpoint.
func GetAutomationEndpoint(handler func(ctx context.Context, params *GetAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetAutomationParams creates a new GetAutomationParams object
// with the default values initialized.
func NewGetAutomationParams() *GetAutomationParams {
var ()
return &GetAutomationParams{}
}
// GetAutomationParams contains all the bound params for the get automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters getAutomation
type GetAutomationParams struct {
/*Automation ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetAutomationParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListAutomationsEndpoint executes the core logic of the related
// route endpoint.
func ListAutomationsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListAutomationsParams creates a new ListAutomationsParams object
// with the default values initialized.
func NewListAutomationsParams() *ListAutomationsParams {
var ()
return &ListAutomationsParams{}
}
// ListAutomationsParams contains all the bound params for the list automations operation
// typically these are obtained from a http.Request
//
// swagger:parameters listAutomations
type ListAutomationsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListAutomationsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateAutomationEndpoint executes the core logic of the related
// route endpoint.
func UpdateAutomationEndpoint(handler func(ctx context.Context, params *UpdateAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateAutomationParams creates a new UpdateAutomationParams object
// with the default values initialized.
func NewUpdateAutomationParams() *UpdateAutomationParams {
var ()
return &UpdateAutomationParams{}
}
// UpdateAutomationParams contains all the bound params for the update automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateAutomation
type UpdateAutomationParams struct {
/*Automation object that needs to be added
Required: true
In: body
*/
Automation *models.AutomationForm
/*Automation ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.AutomationForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("automation", "body", ""))
} else {
res = append(res, errors.NewParseError("automation", "body", "", err))
}
} else {
o.Automation = &body
}
} else {
res = append(res, errors.Required("automation", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateAutomationParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetJobEndpoint executes the core logic of the related
// route endpoint.
func GetJobEndpoint(handler func(ctx context.Context, params *GetJobParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetJobParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetJobParams creates a new GetJobParams object
// with the default values initialized.
func NewGetJobParams() *GetJobParams {
var ()
return &GetJobParams{}
}
// GetJobParams contains all the bound params for the get job operation
// typically these are obtained from a http.Request
//
// swagger:parameters getJob
type GetJobParams struct {
/*Job ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetJobParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetJobParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListJobsEndpoint executes the core logic of the related
// route endpoint.
func ListJobsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListJobsParams creates a new ListJobsParams object
// with the default values initialized.
func NewListJobsParams() *ListJobsParams {
var ()
return &ListJobsParams{}
}
// ListJobsParams contains all the bound params for the list jobs operation
// typically these are obtained from a http.Request
//
// swagger:parameters listJobs
type ListJobsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListJobsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,90 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RunJobEndpoint executes the core logic of the related
// route endpoint.
func RunJobEndpoint(handler func(ctx context.Context, params *RunJobParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRunJobParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRunJobParams creates a new RunJobParams object
// with the default values initialized.
func NewRunJobParams() *RunJobParams {
var ()
return &RunJobParams{}
}
// RunJobParams contains all the bound params for the run job operation
// typically these are obtained from a http.Request
//
// swagger:parameters runJob
type RunJobParams struct {
/*New job
Required: true
In: body
*/
Job *models.JobForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RunJobParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.JobForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("job", "body", ""))
} else {
res = append(res, errors.NewParseError("job", "body", "", err))
}
} else {
o.Job = &body
}
} else {
res = append(res, errors.Required("job", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateJobEndpoint executes the core logic of the related
// route endpoint.
func UpdateJobEndpoint(handler func(ctx context.Context, params *UpdateJobParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateJobParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateJobParams creates a new UpdateJobParams object
// with the default values initialized.
func NewUpdateJobParams() *UpdateJobParams {
var ()
return &UpdateJobParams{}
}
// UpdateJobParams contains all the bound params for the update job operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateJob
type UpdateJobParams struct {
/*Job ID
Required: true
In: path
*/
ID string
/*Job object that needs to be added
Required: true
In: body
*/
Job *models.Job
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateJobParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.Job
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("job", "body", ""))
} else {
res = append(res, errors.NewParseError("job", "body", "", err))
}
} else {
o.Job = &body
}
} else {
res = append(res, errors.Required("job", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateJobParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package logs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetLogsEndpoint executes the core logic of the related
// route endpoint.
func GetLogsEndpoint(handler func(ctx context.Context, params *GetLogsParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetLogsParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetLogsParams creates a new GetLogsParams object
// with the default values initialized.
func NewGetLogsParams() *GetLogsParams {
var ()
return &GetLogsParams{}
}
// GetLogsParams contains all the bound params for the get logs operation
// typically these are obtained from a http.Request
//
// swagger:parameters getLogs
type GetLogsParams struct {
/*Reference
Required: true
In: path
*/
Reference string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetLogsParams) ReadRequest(ctx *gin.Context) error {
var res []error
rReference := []string{ctx.Param("reference")}
if err := o.bindReference(rReference, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetLogsParams) bindReference(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Reference = raw
return nil
}

View File

@@ -1,90 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreatePlaybookEndpoint executes the core logic of the related
// route endpoint.
func CreatePlaybookEndpoint(handler func(ctx context.Context, params *CreatePlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreatePlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreatePlaybookParams creates a new CreatePlaybookParams object
// with the default values initialized.
func NewCreatePlaybookParams() *CreatePlaybookParams {
var ()
return &CreatePlaybookParams{}
}
// CreatePlaybookParams contains all the bound params for the create playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters createPlaybook
type CreatePlaybookParams struct {
/*New playbook
Required: true
In: body
*/
Playbook *models.PlaybookTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreatePlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.PlaybookTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("playbook", "body", ""))
} else {
res = append(res, errors.NewParseError("playbook", "body", "", err))
}
} else {
o.Playbook = &body
}
} else {
res = append(res, errors.Required("playbook", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,87 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeletePlaybookEndpoint executes the core logic of the related
// route endpoint.
func DeletePlaybookEndpoint(handler func(ctx context.Context, params *DeletePlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeletePlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeletePlaybookParams creates a new DeletePlaybookParams object
// with the default values initialized.
func NewDeletePlaybookParams() *DeletePlaybookParams {
var ()
return &DeletePlaybookParams{}
}
// DeletePlaybookParams contains all the bound params for the delete playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters deletePlaybook
type DeletePlaybookParams struct {
/*Playbook name
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeletePlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeletePlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetPlaybookEndpoint executes the core logic of the related
// route endpoint.
func GetPlaybookEndpoint(handler func(ctx context.Context, params *GetPlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetPlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetPlaybookParams creates a new GetPlaybookParams object
// with the default values initialized.
func NewGetPlaybookParams() *GetPlaybookParams {
var ()
return &GetPlaybookParams{}
}
// GetPlaybookParams contains all the bound params for the get playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters getPlaybook
type GetPlaybookParams struct {
/*Playbook name
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetPlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetPlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListPlaybooksEndpoint executes the core logic of the related
// route endpoint.
func ListPlaybooksEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListPlaybooksParams creates a new ListPlaybooksParams object
// with the default values initialized.
func NewListPlaybooksParams() *ListPlaybooksParams {
var ()
return &ListPlaybooksParams{}
}
// ListPlaybooksParams contains all the bound params for the list playbooks operation
// typically these are obtained from a http.Request
//
// swagger:parameters listPlaybooks
type ListPlaybooksParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListPlaybooksParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdatePlaybookEndpoint executes the core logic of the related
// route endpoint.
func UpdatePlaybookEndpoint(handler func(ctx context.Context, params *UpdatePlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdatePlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdatePlaybookParams creates a new UpdatePlaybookParams object
// with the default values initialized.
func NewUpdatePlaybookParams() *UpdatePlaybookParams {
var ()
return &UpdatePlaybookParams{}
}
// UpdatePlaybookParams contains all the bound params for the update playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters updatePlaybook
type UpdatePlaybookParams struct {
/*Playbook ID
Required: true
In: path
*/
ID string
/*Updated playbook
Required: true
In: body
*/
Playbook *models.PlaybookTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdatePlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.PlaybookTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("playbook", "body", ""))
} else {
res = append(res, errors.NewParseError("playbook", "body", "", err))
}
} else {
o.Playbook = &body
}
} else {
res = append(res, errors.Required("playbook", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdatePlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package settings
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetSettingsEndpoint executes the core logic of the related
// route endpoint.
func GetSettingsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetSettingsParams creates a new GetSettingsParams object
// with the default values initialized.
func NewGetSettingsParams() *GetSettingsParams {
var ()
return &GetSettingsParams{}
}
// GetSettingsParams contains all the bound params for the get settings operation
// typically these are obtained from a http.Request
//
// swagger:parameters getSettings
type GetSettingsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetSettingsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,55 +0,0 @@
package statistics
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetStatisticsEndpoint executes the core logic of the related
// route endpoint.
func GetStatisticsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetStatisticsParams creates a new GetStatisticsParams object
// with the default values initialized.
func NewGetStatisticsParams() *GetStatisticsParams {
var ()
return &GetStatisticsParams{}
}
// GetStatisticsParams contains all the bound params for the get statistics operation
// typically these are obtained from a http.Request
//
// swagger:parameters getStatistics
type GetStatisticsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetStatisticsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,55 +0,0 @@
package tasks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListTasksEndpoint executes the core logic of the related
// route endpoint.
func ListTasksEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListTasksParams creates a new ListTasksParams object
// with the default values initialized.
func NewListTasksParams() *ListTasksParams {
var ()
return &ListTasksParams{}
}
// ListTasksParams contains all the bound params for the list tasks operation
// typically these are obtained from a http.Request
//
// swagger:parameters listTasks
type ListTasksParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListTasksParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,90 +0,0 @@
package templates
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreateTemplateEndpoint executes the core logic of the related
// route endpoint.
func CreateTemplateEndpoint(handler func(ctx context.Context, params *CreateTemplateParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreateTemplateParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreateTemplateParams creates a new CreateTemplateParams object
// with the default values initialized.
func NewCreateTemplateParams() *CreateTemplateParams {
var ()
return &CreateTemplateParams{}
}
// CreateTemplateParams contains all the bound params for the create template operation
// typically these are obtained from a http.Request
//
// swagger:parameters createTemplate
type CreateTemplateParams struct {
/*New template
Required: true
In: body
*/
Template *models.TicketTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreateTemplateParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.TicketTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("template", "body", ""))
} else {
res = append(res, errors.NewParseError("template", "body", "", err))
}
} else {
o.Template = &body
}
} else {
res = append(res, errors.Required("template", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,87 +0,0 @@
package templates
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeleteTemplateEndpoint executes the core logic of the related
// route endpoint.
func DeleteTemplateEndpoint(handler func(ctx context.Context, params *DeleteTemplateParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeleteTemplateParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeleteTemplateParams creates a new DeleteTemplateParams object
// with the default values initialized.
func NewDeleteTemplateParams() *DeleteTemplateParams {
var ()
return &DeleteTemplateParams{}
}
// DeleteTemplateParams contains all the bound params for the delete template operation
// typically these are obtained from a http.Request
//
// swagger:parameters deleteTemplate
type DeleteTemplateParams struct {
/*Template ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeleteTemplateParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeleteTemplateParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package templates
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetTemplateEndpoint executes the core logic of the related
// route endpoint.
func GetTemplateEndpoint(handler func(ctx context.Context, params *GetTemplateParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetTemplateParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetTemplateParams creates a new GetTemplateParams object
// with the default values initialized.
func NewGetTemplateParams() *GetTemplateParams {
var ()
return &GetTemplateParams{}
}
// GetTemplateParams contains all the bound params for the get template operation
// typically these are obtained from a http.Request
//
// swagger:parameters getTemplate
type GetTemplateParams struct {
/*Template ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetTemplateParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetTemplateParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package templates
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListTemplatesEndpoint executes the core logic of the related
// route endpoint.
func ListTemplatesEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListTemplatesParams creates a new ListTemplatesParams object
// with the default values initialized.
func NewListTemplatesParams() *ListTemplatesParams {
var ()
return &ListTemplatesParams{}
}
// ListTemplatesParams contains all the bound params for the list templates operation
// typically these are obtained from a http.Request
//
// swagger:parameters listTemplates
type ListTemplatesParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListTemplatesParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package templates
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateTemplateEndpoint executes the core logic of the related
// route endpoint.
func UpdateTemplateEndpoint(handler func(ctx context.Context, params *UpdateTemplateParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateTemplateParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateTemplateParams creates a new UpdateTemplateParams object
// with the default values initialized.
func NewUpdateTemplateParams() *UpdateTemplateParams {
var ()
return &UpdateTemplateParams{}
}
// UpdateTemplateParams contains all the bound params for the update template operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateTemplate
type UpdateTemplateParams struct {
/*Template ID
Required: true
In: path
*/
ID string
/*Template object that needs to be added
Required: true
In: body
*/
Template *models.TicketTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateTemplateParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.TicketTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("template", "body", ""))
} else {
res = append(res, errors.NewParseError("template", "body", "", err))
}
} else {
o.Template = &body
}
} else {
res = append(res, errors.Required("template", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateTemplateParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,116 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// AddArtifactEndpoint executes the core logic of the related
// route endpoint.
func AddArtifactEndpoint(handler func(ctx context.Context, params *AddArtifactParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewAddArtifactParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewAddArtifactParams creates a new AddArtifactParams object
// with the default values initialized.
func NewAddArtifactParams() *AddArtifactParams {
var ()
return &AddArtifactParams{}
}
// AddArtifactParams contains all the bound params for the add artifact operation
// typically these are obtained from a http.Request
//
// swagger:parameters addArtifact
type AddArtifactParams struct {
/*Artifact object that needs to be added
Required: true
In: body
*/
Artifact *models.Artifact
/*Ticket ID
Required: true
In: path
*/
ID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *AddArtifactParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.Artifact
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("artifact", "body", ""))
} else {
res = append(res, errors.NewParseError("artifact", "body", "", err))
}
} else {
o.Artifact = &body
}
} else {
res = append(res, errors.Required("artifact", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *AddArtifactParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,116 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// AddCommentEndpoint executes the core logic of the related
// route endpoint.
func AddCommentEndpoint(handler func(ctx context.Context, params *AddCommentParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewAddCommentParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewAddCommentParams creates a new AddCommentParams object
// with the default values initialized.
func NewAddCommentParams() *AddCommentParams {
var ()
return &AddCommentParams{}
}
// AddCommentParams contains all the bound params for the add comment operation
// typically these are obtained from a http.Request
//
// swagger:parameters addComment
type AddCommentParams struct {
/*Ticket comment
Required: true
In: body
*/
Comment *models.CommentForm
/*Ticket ID
Required: true
In: path
*/
ID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *AddCommentParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.CommentForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("comment", "body", ""))
} else {
res = append(res, errors.NewParseError("comment", "body", "", err))
}
} else {
o.Comment = &body
}
} else {
res = append(res, errors.Required("comment", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *AddCommentParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,116 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// AddTicketPlaybookEndpoint executes the core logic of the related
// route endpoint.
func AddTicketPlaybookEndpoint(handler func(ctx context.Context, params *AddTicketPlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewAddTicketPlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewAddTicketPlaybookParams creates a new AddTicketPlaybookParams object
// with the default values initialized.
func NewAddTicketPlaybookParams() *AddTicketPlaybookParams {
var ()
return &AddTicketPlaybookParams{}
}
// AddTicketPlaybookParams contains all the bound params for the add ticket playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters addTicketPlaybook
type AddTicketPlaybookParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Ticket playbook object that needs to be added
Required: true
In: body
*/
Playbook *models.PlaybookTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *AddTicketPlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.PlaybookTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("playbook", "body", ""))
} else {
res = append(res, errors.NewParseError("playbook", "body", "", err))
}
} else {
o.Playbook = &body
}
} else {
res = append(res, errors.Required("playbook", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *AddTicketPlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,157 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CompleteTaskEndpoint executes the core logic of the related
// route endpoint.
func CompleteTaskEndpoint(handler func(ctx context.Context, params *CompleteTaskParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCompleteTaskParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCompleteTaskParams creates a new CompleteTaskParams object
// with the default values initialized.
func NewCompleteTaskParams() *CompleteTaskParams {
var ()
return &CompleteTaskParams{}
}
// CompleteTaskParams contains all the bound params for the complete task operation
// typically these are obtained from a http.Request
//
// swagger:parameters completeTask
type CompleteTaskParams struct {
/*Ticket playbook object that needs to be added
Required: true
In: body
*/
Data interface{}
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Playbook ID
Required: true
In: path
*/
PlaybookID string
/*Task ID
Required: true
In: path
*/
TaskID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CompleteTaskParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body interface{}
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("data", "body", ""))
} else {
res = append(res, errors.NewParseError("data", "body", "", err))
}
} else {
o.Data = body
}
} else {
res = append(res, errors.Required("data", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rPlaybookID := []string{ctx.Param("playbookID")}
if err := o.bindPlaybookID(rPlaybookID, true); err != nil {
res = append(res, err)
}
rTaskID := []string{ctx.Param("taskID")}
if err := o.bindTaskID(rTaskID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *CompleteTaskParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *CompleteTaskParams) bindPlaybookID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.PlaybookID = raw
return nil
}
func (o *CompleteTaskParams) bindTaskID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.TaskID = raw
return nil
}

View File

@@ -1,90 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreateTicketBatchEndpoint executes the core logic of the related
// route endpoint.
func CreateTicketBatchEndpoint(handler func(ctx context.Context, params *CreateTicketBatchParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreateTicketBatchParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreateTicketBatchParams creates a new CreateTicketBatchParams object
// with the default values initialized.
func NewCreateTicketBatchParams() *CreateTicketBatchParams {
var ()
return &CreateTicketBatchParams{}
}
// CreateTicketBatchParams contains all the bound params for the create ticket batch operation
// typically these are obtained from a http.Request
//
// swagger:parameters createTicketBatch
type CreateTicketBatchParams struct {
/*New ticket
Required: true
In: body
*/
Ticket []*models.TicketForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreateTicketBatchParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body []*models.TicketForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("ticket", "body", ""))
} else {
res = append(res, errors.NewParseError("ticket", "body", "", err))
}
} else {
o.Ticket = body
}
} else {
res = append(res, errors.Required("ticket", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,90 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreateTicketEndpoint executes the core logic of the related
// route endpoint.
func CreateTicketEndpoint(handler func(ctx context.Context, params *CreateTicketParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreateTicketParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreateTicketParams creates a new CreateTicketParams object
// with the default values initialized.
func NewCreateTicketParams() *CreateTicketParams {
var ()
return &CreateTicketParams{}
}
// CreateTicketParams contains all the bound params for the create ticket operation
// typically these are obtained from a http.Request
//
// swagger:parameters createTicket
type CreateTicketParams struct {
/*New ticket
Required: true
In: body
*/
Ticket *models.TicketForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreateTicketParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.TicketForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("ticket", "body", ""))
} else {
res = append(res, errors.NewParseError("ticket", "body", "", err))
}
} else {
o.Ticket = &body
}
} else {
res = append(res, errors.Required("ticket", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,92 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeleteTicketEndpoint executes the core logic of the related
// route endpoint.
func DeleteTicketEndpoint(handler func(ctx context.Context, params *DeleteTicketParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeleteTicketParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeleteTicketParams creates a new DeleteTicketParams object
// with the default values initialized.
func NewDeleteTicketParams() *DeleteTicketParams {
var ()
return &DeleteTicketParams{}
}
// DeleteTicketParams contains all the bound params for the delete ticket operation
// typically these are obtained from a http.Request
//
// swagger:parameters deleteTicket
type DeleteTicketParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeleteTicketParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeleteTicketParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,137 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// EnrichArtifactEndpoint executes the core logic of the related
// route endpoint.
func EnrichArtifactEndpoint(handler func(ctx context.Context, params *EnrichArtifactParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewEnrichArtifactParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewEnrichArtifactParams creates a new EnrichArtifactParams object
// with the default values initialized.
func NewEnrichArtifactParams() *EnrichArtifactParams {
var ()
return &EnrichArtifactParams{}
}
// EnrichArtifactParams contains all the bound params for the enrich artifact operation
// typically these are obtained from a http.Request
//
// swagger:parameters enrichArtifact
type EnrichArtifactParams struct {
/*
Required: true
In: body
*/
Data *models.EnrichmentForm
/*Ticket ID
Required: true
In: path
*/
ID int64
/*
Required: true
In: path
*/
Name string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *EnrichArtifactParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.EnrichmentForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("data", "body", ""))
} else {
res = append(res, errors.NewParseError("data", "body", "", err))
}
} else {
o.Data = &body
}
} else {
res = append(res, errors.Required("data", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rName := []string{ctx.Param("name")}
if err := o.bindName(rName, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *EnrichArtifactParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *EnrichArtifactParams) bindName(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Name = raw
return nil
}

View File

@@ -1,113 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetArtifactEndpoint executes the core logic of the related
// route endpoint.
func GetArtifactEndpoint(handler func(ctx context.Context, params *GetArtifactParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetArtifactParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetArtifactParams creates a new GetArtifactParams object
// with the default values initialized.
func NewGetArtifactParams() *GetArtifactParams {
var ()
return &GetArtifactParams{}
}
// GetArtifactParams contains all the bound params for the get artifact operation
// typically these are obtained from a http.Request
//
// swagger:parameters getArtifact
type GetArtifactParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*
Required: true
In: path
*/
Name string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetArtifactParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rName := []string{ctx.Param("name")}
if err := o.bindName(rName, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetArtifactParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *GetArtifactParams) bindName(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Name = raw
return nil
}

View File

@@ -1,92 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetTicketEndpoint executes the core logic of the related
// route endpoint.
func GetTicketEndpoint(handler func(ctx context.Context, params *GetTicketParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetTicketParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetTicketParams creates a new GetTicketParams object
// with the default values initialized.
func NewGetTicketParams() *GetTicketParams {
var ()
return &GetTicketParams{}
}
// GetTicketParams contains all the bound params for the get ticket operation
// typically these are obtained from a http.Request
//
// swagger:parameters getTicket
type GetTicketParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetTicketParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetTicketParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,116 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// LinkFilesEndpoint executes the core logic of the related
// route endpoint.
func LinkFilesEndpoint(handler func(ctx context.Context, params *LinkFilesParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewLinkFilesParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewLinkFilesParams creates a new LinkFilesParams object
// with the default values initialized.
func NewLinkFilesParams() *LinkFilesParams {
var ()
return &LinkFilesParams{}
}
// LinkFilesParams contains all the bound params for the link files operation
// typically these are obtained from a http.Request
//
// swagger:parameters linkFiles
type LinkFilesParams struct {
/*Added files
Required: true
In: body
*/
Files []*models.File
/*Ticket ID
Required: true
In: path
*/
ID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *LinkFilesParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body []*models.File
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("files", "body", ""))
} else {
res = append(res, errors.NewParseError("files", "body", "", err))
}
} else {
o.Files = body
}
} else {
res = append(res, errors.Required("files", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *LinkFilesParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,115 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// LinkTicketEndpoint executes the core logic of the related
// route endpoint.
func LinkTicketEndpoint(handler func(ctx context.Context, params *LinkTicketParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewLinkTicketParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewLinkTicketParams creates a new LinkTicketParams object
// with the default values initialized.
func NewLinkTicketParams() *LinkTicketParams {
var ()
return &LinkTicketParams{}
}
// LinkTicketParams contains all the bound params for the link ticket operation
// typically these are obtained from a http.Request
//
// swagger:parameters linkTicket
type LinkTicketParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Added ticket ID
Required: true
In: body
*/
LinkedID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *LinkTicketParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body int64
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("linkedId", "body", ""))
} else {
res = append(res, errors.NewParseError("linkedId", "body", "", err))
}
} else {
o.LinkedID = body
}
} else {
res = append(res, errors.Required("linkedId", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *LinkTicketParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,269 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListTicketsEndpoint executes the core logic of the related
// route endpoint.
func ListTicketsEndpoint(handler func(ctx context.Context, params *ListTicketsParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewListTicketsParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListTicketsParams creates a new ListTicketsParams object
// with the default values initialized.
func NewListTicketsParams() *ListTicketsParams {
var (
countDefault = int64(25)
offsetDefault = int64(0)
)
return &ListTicketsParams{
Count: &countDefault,
Offset: &offsetDefault,
}
}
// ListTicketsParams contains all the bound params for the list tickets operation
// typically these are obtained from a http.Request
//
// swagger:parameters listTickets
type ListTicketsParams struct {
/*Number of tickets
Maximum: 100
In: query
Default: 25
*/
Count *int64
/*Sort descending
In: query
*/
Desc []bool
/*Offset of the list
In: query
Default: 0
*/
Offset *int64
/*Search query
In: query
*/
Query *string
/*Sort columns
In: query
*/
Sort []string
/*Ticket Type
In: query
*/
Type *string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListTicketsParams) ReadRequest(ctx *gin.Context) error {
var res []error
qs := runtime.Values(ctx.Request.URL.Query())
qCount, qhkCount, _ := qs.GetOK("count")
if err := o.bindCount(qCount, qhkCount); err != nil {
res = append(res, err)
}
qDesc, qhkDesc, _ := qs.GetOK("desc")
if err := o.bindDesc(qDesc, qhkDesc); err != nil {
res = append(res, err)
}
qOffset, qhkOffset, _ := qs.GetOK("offset")
if err := o.bindOffset(qOffset, qhkOffset); err != nil {
res = append(res, err)
}
qQuery, qhkQuery, _ := qs.GetOK("query")
if err := o.bindQuery(qQuery, qhkQuery); err != nil {
res = append(res, err)
}
qSort, qhkSort, _ := qs.GetOK("sort")
if err := o.bindSort(qSort, qhkSort); err != nil {
res = append(res, err)
}
qType, qhkType, _ := qs.GetOK("type")
if err := o.bindType(qType, qhkType); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *ListTicketsParams) bindCount(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
if raw == "" { // empty values pass all other validations
var countDefault int64 = int64(25)
o.Count = &countDefault
return nil
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("count", "query", "int64", raw)
}
o.Count = &value
if err := o.validateCount(); err != nil {
return err
}
return nil
}
func (o *ListTicketsParams) validateCount() error {
if err := validate.MaximumInt("count", "query", int64(*o.Count), 100, false); err != nil {
return err
}
return nil
}
func (o *ListTicketsParams) bindDesc(rawData []string, hasKey bool) error {
var qvDesc string
if len(rawData) > 0 {
qvDesc = rawData[len(rawData)-1]
}
descIC := swag.SplitByFormat(qvDesc, "")
if len(descIC) == 0 {
return nil
}
var descIR []bool
for i, descIV := range descIC {
descI, err := swag.ConvertBool(descIV)
if err != nil {
return errors.InvalidType(fmt.Sprintf("%s.%v", "desc", i), "query", "bool", descI)
}
descIR = append(descIR, descI)
}
o.Desc = descIR
return nil
}
func (o *ListTicketsParams) bindOffset(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
if raw == "" { // empty values pass all other validations
var offsetDefault int64 = int64(0)
o.Offset = &offsetDefault
return nil
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("offset", "query", "int64", raw)
}
o.Offset = &value
return nil
}
func (o *ListTicketsParams) bindQuery(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
if raw == "" { // empty values pass all other validations
return nil
}
o.Query = &raw
return nil
}
func (o *ListTicketsParams) bindSort(rawData []string, hasKey bool) error {
var qvSort string
if len(rawData) > 0 {
qvSort = rawData[len(rawData)-1]
}
sortIC := swag.SplitByFormat(qvSort, "")
if len(sortIC) == 0 {
return nil
}
var sortIR []string
for _, sortIV := range sortIC {
sortI := sortIV
sortIR = append(sortIR, sortI)
}
o.Sort = sortIR
return nil
}
func (o *ListTicketsParams) bindType(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
if raw == "" { // empty values pass all other validations
return nil
}
o.Type = &raw
return nil
}

View File

@@ -1,113 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RemoveArtifactEndpoint executes the core logic of the related
// route endpoint.
func RemoveArtifactEndpoint(handler func(ctx context.Context, params *RemoveArtifactParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRemoveArtifactParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRemoveArtifactParams creates a new RemoveArtifactParams object
// with the default values initialized.
func NewRemoveArtifactParams() *RemoveArtifactParams {
var ()
return &RemoveArtifactParams{}
}
// RemoveArtifactParams contains all the bound params for the remove artifact operation
// typically these are obtained from a http.Request
//
// swagger:parameters removeArtifact
type RemoveArtifactParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*
Required: true
In: path
*/
Name string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RemoveArtifactParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rName := []string{ctx.Param("name")}
if err := o.bindName(rName, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *RemoveArtifactParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *RemoveArtifactParams) bindName(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Name = raw
return nil
}

View File

@@ -1,117 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RemoveCommentEndpoint executes the core logic of the related
// route endpoint.
func RemoveCommentEndpoint(handler func(ctx context.Context, params *RemoveCommentParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRemoveCommentParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRemoveCommentParams creates a new RemoveCommentParams object
// with the default values initialized.
func NewRemoveCommentParams() *RemoveCommentParams {
var ()
return &RemoveCommentParams{}
}
// RemoveCommentParams contains all the bound params for the remove comment operation
// typically these are obtained from a http.Request
//
// swagger:parameters removeComment
type RemoveCommentParams struct {
/*Comment ID to remove
Required: true
In: path
*/
CommentID int64
/*Ticket ID
Required: true
In: path
*/
ID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RemoveCommentParams) ReadRequest(ctx *gin.Context) error {
var res []error
rCommentID := []string{ctx.Param("commentID")}
if err := o.bindCommentID(rCommentID, true); err != nil {
res = append(res, err)
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *RemoveCommentParams) bindCommentID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("commentID", "path", "int64", raw)
}
o.CommentID = value
return nil
}
func (o *RemoveCommentParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,113 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RemoveTicketPlaybookEndpoint executes the core logic of the related
// route endpoint.
func RemoveTicketPlaybookEndpoint(handler func(ctx context.Context, params *RemoveTicketPlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRemoveTicketPlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRemoveTicketPlaybookParams creates a new RemoveTicketPlaybookParams object
// with the default values initialized.
func NewRemoveTicketPlaybookParams() *RemoveTicketPlaybookParams {
var ()
return &RemoveTicketPlaybookParams{}
}
// RemoveTicketPlaybookParams contains all the bound params for the remove ticket playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters removeTicketPlaybook
type RemoveTicketPlaybookParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Playbook ID
Required: true
In: path
*/
PlaybookID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RemoveTicketPlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rPlaybookID := []string{ctx.Param("playbookID")}
if err := o.bindPlaybookID(rPlaybookID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *RemoveTicketPlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *RemoveTicketPlaybookParams) bindPlaybookID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.PlaybookID = raw
return nil
}

View File

@@ -1,134 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RunArtifactEndpoint executes the core logic of the related
// route endpoint.
func RunArtifactEndpoint(handler func(ctx context.Context, params *RunArtifactParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRunArtifactParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRunArtifactParams creates a new RunArtifactParams object
// with the default values initialized.
func NewRunArtifactParams() *RunArtifactParams {
var ()
return &RunArtifactParams{}
}
// RunArtifactParams contains all the bound params for the run artifact operation
// typically these are obtained from a http.Request
//
// swagger:parameters runArtifact
type RunArtifactParams struct {
/*
Required: true
In: path
*/
Automation string
/*Ticket ID
Required: true
In: path
*/
ID int64
/*
Required: true
In: path
*/
Name string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RunArtifactParams) ReadRequest(ctx *gin.Context) error {
var res []error
rAutomation := []string{ctx.Param("automation")}
if err := o.bindAutomation(rAutomation, true); err != nil {
res = append(res, err)
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rName := []string{ctx.Param("name")}
if err := o.bindName(rName, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *RunArtifactParams) bindAutomation(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Automation = raw
return nil
}
func (o *RunArtifactParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *RunArtifactParams) bindName(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Name = raw
return nil
}

View File

@@ -1,134 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RunTaskEndpoint executes the core logic of the related
// route endpoint.
func RunTaskEndpoint(handler func(ctx context.Context, params *RunTaskParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRunTaskParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRunTaskParams creates a new RunTaskParams object
// with the default values initialized.
func NewRunTaskParams() *RunTaskParams {
var ()
return &RunTaskParams{}
}
// RunTaskParams contains all the bound params for the run task operation
// typically these are obtained from a http.Request
//
// swagger:parameters runTask
type RunTaskParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Playbook ID
Required: true
In: path
*/
PlaybookID string
/*Task ID
Required: true
In: path
*/
TaskID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RunTaskParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rPlaybookID := []string{ctx.Param("playbookID")}
if err := o.bindPlaybookID(rPlaybookID, true); err != nil {
res = append(res, err)
}
rTaskID := []string{ctx.Param("taskID")}
if err := o.bindTaskID(rTaskID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *RunTaskParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *RunTaskParams) bindPlaybookID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.PlaybookID = raw
return nil
}
func (o *RunTaskParams) bindTaskID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.TaskID = raw
return nil
}

View File

@@ -1,137 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// SetArtifactEndpoint executes the core logic of the related
// route endpoint.
func SetArtifactEndpoint(handler func(ctx context.Context, params *SetArtifactParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewSetArtifactParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewSetArtifactParams creates a new SetArtifactParams object
// with the default values initialized.
func NewSetArtifactParams() *SetArtifactParams {
var ()
return &SetArtifactParams{}
}
// SetArtifactParams contains all the bound params for the set artifact operation
// typically these are obtained from a http.Request
//
// swagger:parameters setArtifact
type SetArtifactParams struct {
/*
Required: true
In: body
*/
Artifact *models.Artifact
/*Ticket ID
Required: true
In: path
*/
ID int64
/*
Required: true
In: path
*/
Name string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *SetArtifactParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.Artifact
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("artifact", "body", ""))
} else {
res = append(res, errors.NewParseError("artifact", "body", "", err))
}
} else {
o.Artifact = &body
}
} else {
res = append(res, errors.Required("artifact", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rName := []string{ctx.Param("name")}
if err := o.bindName(rName, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *SetArtifactParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *SetArtifactParams) bindName(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Name = raw
return nil
}

View File

@@ -1,116 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// SetReferencesEndpoint executes the core logic of the related
// route endpoint.
func SetReferencesEndpoint(handler func(ctx context.Context, params *SetReferencesParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewSetReferencesParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewSetReferencesParams creates a new SetReferencesParams object
// with the default values initialized.
func NewSetReferencesParams() *SetReferencesParams {
var ()
return &SetReferencesParams{}
}
// SetReferencesParams contains all the bound params for the set references operation
// typically these are obtained from a http.Request
//
// swagger:parameters setReferences
type SetReferencesParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*All ticket references
Required: true
In: body
*/
References []*models.Reference
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *SetReferencesParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body []*models.Reference
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("references", "body", ""))
} else {
res = append(res, errors.NewParseError("references", "body", "", err))
}
} else {
o.References = body
}
} else {
res = append(res, errors.Required("references", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *SetReferencesParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,106 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// SetSchemaEndpoint executes the core logic of the related
// route endpoint.
func SetSchemaEndpoint(handler func(ctx context.Context, params *SetSchemaParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewSetSchemaParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewSetSchemaParams creates a new SetSchemaParams object
// with the default values initialized.
func NewSetSchemaParams() *SetSchemaParams {
var ()
return &SetSchemaParams{}
}
// SetSchemaParams contains all the bound params for the set schema operation
// typically these are obtained from a http.Request
//
// swagger:parameters setSchema
type SetSchemaParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*New ticket schema
In: body
*/
Schema string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *SetSchemaParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body string
if err := ctx.BindJSON(&body); err != nil {
res = append(res, errors.NewParseError("schema", "body", "", err))
} else {
o.Schema = body
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *SetSchemaParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,158 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// SetTaskEndpoint executes the core logic of the related
// route endpoint.
func SetTaskEndpoint(handler func(ctx context.Context, params *SetTaskParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewSetTaskParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewSetTaskParams creates a new SetTaskParams object
// with the default values initialized.
func NewSetTaskParams() *SetTaskParams {
var ()
return &SetTaskParams{}
}
// SetTaskParams contains all the bound params for the set task operation
// typically these are obtained from a http.Request
//
// swagger:parameters setTask
type SetTaskParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Playbook ID
Required: true
In: path
*/
PlaybookID string
/*Task
Required: true
In: body
*/
Task *models.Task
/*Task ID
Required: true
In: path
*/
TaskID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *SetTaskParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
rPlaybookID := []string{ctx.Param("playbookID")}
if err := o.bindPlaybookID(rPlaybookID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.Task
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("task", "body", ""))
} else {
res = append(res, errors.NewParseError("task", "body", "", err))
}
} else {
o.Task = &body
}
} else {
res = append(res, errors.Required("task", "body", ""))
}
rTaskID := []string{ctx.Param("taskID")}
if err := o.bindTaskID(rTaskID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *SetTaskParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}
func (o *SetTaskParams) bindPlaybookID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.PlaybookID = raw
return nil
}
func (o *SetTaskParams) bindTaskID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.TaskID = raw
return nil
}

View File

@@ -1,115 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UnlinkTicketEndpoint executes the core logic of the related
// route endpoint.
func UnlinkTicketEndpoint(handler func(ctx context.Context, params *UnlinkTicketParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUnlinkTicketParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUnlinkTicketParams creates a new UnlinkTicketParams object
// with the default values initialized.
func NewUnlinkTicketParams() *UnlinkTicketParams {
var ()
return &UnlinkTicketParams{}
}
// UnlinkTicketParams contains all the bound params for the unlink ticket operation
// typically these are obtained from a http.Request
//
// swagger:parameters unlinkTicket
type UnlinkTicketParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Added ticket ID
Required: true
In: body
*/
LinkedID int64
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UnlinkTicketParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body int64
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("linkedId", "body", ""))
} else {
res = append(res, errors.NewParseError("linkedId", "body", "", err))
}
} else {
o.LinkedID = body
}
} else {
res = append(res, errors.Required("linkedId", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UnlinkTicketParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,116 +0,0 @@
package tickets
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateTicketEndpoint executes the core logic of the related
// route endpoint.
func UpdateTicketEndpoint(handler func(ctx context.Context, params *UpdateTicketParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateTicketParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateTicketParams creates a new UpdateTicketParams object
// with the default values initialized.
func NewUpdateTicketParams() *UpdateTicketParams {
var ()
return &UpdateTicketParams{}
}
// UpdateTicketParams contains all the bound params for the update ticket operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateTicket
type UpdateTicketParams struct {
/*Ticket ID
Required: true
In: path
*/
ID int64
/*Updated ticket
Required: true
In: body
*/
Ticket *models.Ticket
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateTicketParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.Ticket
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("ticket", "body", ""))
} else {
res = append(res, errors.NewParseError("ticket", "body", "", err))
}
} else {
o.Ticket = &body
}
} else {
res = append(res, errors.Required("ticket", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateTicketParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("id", "path", "int64", raw)
}
o.ID = value
return nil
}

View File

@@ -1,90 +0,0 @@
package tickettypes
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreateTicketTypeEndpoint executes the core logic of the related
// route endpoint.
func CreateTicketTypeEndpoint(handler func(ctx context.Context, params *CreateTicketTypeParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreateTicketTypeParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreateTicketTypeParams creates a new CreateTicketTypeParams object
// with the default values initialized.
func NewCreateTicketTypeParams() *CreateTicketTypeParams {
var ()
return &CreateTicketTypeParams{}
}
// CreateTicketTypeParams contains all the bound params for the create ticket type operation
// typically these are obtained from a http.Request
//
// swagger:parameters createTicketType
type CreateTicketTypeParams struct {
/*New tickettype
Required: true
In: body
*/
Tickettype *models.TicketTypeForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreateTicketTypeParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.TicketTypeForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("tickettype", "body", ""))
} else {
res = append(res, errors.NewParseError("tickettype", "body", "", err))
}
} else {
o.Tickettype = &body
}
} else {
res = append(res, errors.Required("tickettype", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,87 +0,0 @@
package tickettypes
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeleteTicketTypeEndpoint executes the core logic of the related
// route endpoint.
func DeleteTicketTypeEndpoint(handler func(ctx context.Context, params *DeleteTicketTypeParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeleteTicketTypeParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeleteTicketTypeParams creates a new DeleteTicketTypeParams object
// with the default values initialized.
func NewDeleteTicketTypeParams() *DeleteTicketTypeParams {
var ()
return &DeleteTicketTypeParams{}
}
// DeleteTicketTypeParams contains all the bound params for the delete ticket type operation
// typically these are obtained from a http.Request
//
// swagger:parameters deleteTicketType
type DeleteTicketTypeParams struct {
/*TicketType ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeleteTicketTypeParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeleteTicketTypeParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package tickettypes
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetTicketTypeEndpoint executes the core logic of the related
// route endpoint.
func GetTicketTypeEndpoint(handler func(ctx context.Context, params *GetTicketTypeParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetTicketTypeParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetTicketTypeParams creates a new GetTicketTypeParams object
// with the default values initialized.
func NewGetTicketTypeParams() *GetTicketTypeParams {
var ()
return &GetTicketTypeParams{}
}
// GetTicketTypeParams contains all the bound params for the get ticket type operation
// typically these are obtained from a http.Request
//
// swagger:parameters getTicketType
type GetTicketTypeParams struct {
/*TicketType ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetTicketTypeParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetTicketTypeParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package tickettypes
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListTicketTypesEndpoint executes the core logic of the related
// route endpoint.
func ListTicketTypesEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListTicketTypesParams creates a new ListTicketTypesParams object
// with the default values initialized.
func NewListTicketTypesParams() *ListTicketTypesParams {
var ()
return &ListTicketTypesParams{}
}
// ListTicketTypesParams contains all the bound params for the list ticket types operation
// typically these are obtained from a http.Request
//
// swagger:parameters listTicketTypes
type ListTicketTypesParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListTicketTypesParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package tickettypes
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateTicketTypeEndpoint executes the core logic of the related
// route endpoint.
func UpdateTicketTypeEndpoint(handler func(ctx context.Context, params *UpdateTicketTypeParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateTicketTypeParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateTicketTypeParams creates a new UpdateTicketTypeParams object
// with the default values initialized.
func NewUpdateTicketTypeParams() *UpdateTicketTypeParams {
var ()
return &UpdateTicketTypeParams{}
}
// UpdateTicketTypeParams contains all the bound params for the update ticket type operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateTicketType
type UpdateTicketTypeParams struct {
/*TicketType ID
Required: true
In: path
*/
ID string
/*TicketType object that needs to be added
Required: true
In: body
*/
Tickettype *models.TicketTypeForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateTicketTypeParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.TicketTypeForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("tickettype", "body", ""))
} else {
res = append(res, errors.NewParseError("tickettype", "body", "", err))
}
} else {
o.Tickettype = &body
}
} else {
res = append(res, errors.Required("tickettype", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateTicketTypeParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package userdata
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CurrentUserDataEndpoint executes the core logic of the related
// route endpoint.
func CurrentUserDataEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCurrentUserDataParams creates a new CurrentUserDataParams object
// with the default values initialized.
func NewCurrentUserDataParams() *CurrentUserDataParams {
var ()
return &CurrentUserDataParams{}
}
// CurrentUserDataParams contains all the bound params for the current user data operation
// typically these are obtained from a http.Request
//
// swagger:parameters currentUserData
type CurrentUserDataParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CurrentUserDataParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

Some files were not shown because too many files have changed in this diff Show More