Skip to content

Commit

Permalink
* fix basic authentication -> rm authz.*
Browse files Browse the repository at this point in the history
  • Loading branch information
JGottschick committed Oct 5, 2024
1 parent 534db0d commit 0b3c0e5
Show file tree
Hide file tree
Showing 8 changed files with 110 additions and 75 deletions.
19 changes: 0 additions & 19 deletions generator/authz.go

This file was deleted.

8 changes: 0 additions & 8 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ const (
DatabasePkg = "db"
EntitiesPkg = "entities"
UsecasesPkg = "usecases"
AuthzPkg = "rest/middleware"
MiddlewarePackage = "rest/middleware"
DefaultPort = 8080
)
Expand Down Expand Up @@ -90,10 +89,6 @@ func GenerateServer(conf GeneratorConfig) error {
generateDatabaseFiles(conf)
}

if conf.AddAuth {
generateAuthzFile(conf)
}

generateValidation(conf)
generatePolicy(conf)

Expand All @@ -116,9 +111,6 @@ func createProjectPathDirectory(conf GeneratorConfig) {
if conf.AddDatabase {
fs.GenerateFolder(filepath.Join(config.Path, DatabasePkg))
}
if conf.AddAuth {
fs.GenerateFolder(filepath.Join(config.Path, AuthzPkg))
}
fs.GenerateFolder(filepath.Join(config.Path, MiddlewarePackage))

log.Info().Msg("Created project directory.")
Expand Down
15 changes: 5 additions & 10 deletions generator/policy.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package generator

import (
fs "dredger/fileUtils"
"errors"
"os"
"path/filepath"

"github.com/rs/zerolog/log"
Expand All @@ -13,18 +14,12 @@ func generatePolicy(conf GeneratorConfig) {
fileName := "policy.go"
filePath := filepath.Join(config.Path, MiddlewarePackage, fileName)
templateFile := "templates/middleware/policy.go.tmpl"
fs.GenerateFile(filePath)
createFileFromTemplate(filePath, templateFile, conf)

fileName = "authz.go"
filePath = filepath.Join(config.Path, MiddlewarePackage, fileName)
templateFile = "templates/middleware/authz.go.tmpl"
fs.GenerateFile(filePath)
createFileFromTemplate(filePath, templateFile, conf)

fileName = "authz.rego"
filePath = filepath.Join(config.Path, MiddlewarePackage, fileName)
templateFile = "templates/middleware/authz.rego.tmpl"
fs.GenerateFile(filePath)
createFileFromTemplate(filePath, templateFile, conf)
if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {
createFileFromTemplate(filePath, templateFile, conf)
}
}
9 changes: 8 additions & 1 deletion templates/Justfile.tmpl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This file was initially generated by dredger, but feel free to adapt it to your needs and environment
set dotenv-load
program := `basename $PWD`
port := env_var_or_default("PORT", "9090")
port := env_var_or_default("{{ upper ( snakecase .ModuleName ) }}_PORT_NB", "9090")

help:
just -l
Expand All @@ -19,6 +19,9 @@ install: build
run: build
go run . -p {{"{{port}}"}}

debug: build
go run . -d -p {{"{{port}}"}}

generate:
dredger generate OpenAPI.yaml -o . -f -n {{ .ModuleName }}

Expand All @@ -43,6 +46,10 @@ docker-run:
required:
go install github.com/a-h/templ/cmd/templ@latest

update: required
go get -u
go mod tidy

# List all ToDo items of the source code
todo:
rg -ip "to.?do:"
Expand Down
1 change: 0 additions & 1 deletion templates/core/config.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ type Config struct {
Title string
PortNb string `default:"8080"` // Port is a reserved name in k8s
ApiKeys []string `default:"" split_words:"true"`
AuthorizationHeader string `default:"" split_words:"true"`
SessionKey string `default:"" split_words:"true"`
Host string `ignored:"true"`
User string
Expand Down
28 changes: 0 additions & 28 deletions templates/middleware/authz.go.tmpl

This file was deleted.

91 changes: 89 additions & 2 deletions templates/middleware/authz.rego.tmpl
Original file line number Diff line number Diff line change
@@ -1,4 +1,91 @@
package {{ lcfirst ( camelcase .ModuleName ) }}.authz

default allowEntrypoint = true
default allowAccess = true
#
# Methods
#

default getMethod = false

getMethod {
lower(input.method) == "get"
}

default putMethod = false

putMethod {
lower(input.method) == "put"
}

default postMethod = false

postMethod {
lower(input.method) == "post"
}

default deleteMethod = false

deleteMethod {
lower(input.method) == "delete"
}

#
# Roles
#

default staff = false

staff {
lower(input.role) == "staff"
}

default user = false

user {
lower(input.role) == "user"
}

default staffuser = false

staffuser {
staff
}

staffuser {
user
}

#
# API token
#

default api = false

api {
lower(input.role) == "api"
}

api {
input.apitoken == ""
}

#
# Rules
#
# allowEntryPoint permit general the access to a api function
# allowAccess check the authorization by the permitted roles
#
default allowEntrypoint = false

default allowAccess = false

allowEntrypoint {
# user
# getMethod
# input.path == "/livez"
}

allowAccess {
# user
# getMethod
# input.path == "/livez"
}
14 changes: 8 additions & 6 deletions templates/middleware/policy.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ func init() {
}

// precompile policy
// log.Debug().Str("policy", core.AppConfig.Policy).Msg("got policy")
log.Debug().Msg("Precompile rego policy")
var err error
policyCompiler, err = ast.CompileModules(map[string]string{
"authz.rego": core.AppConfig.Policy,
})
if err != nil {
log.Printf("wrong rego policy (%s)\n", err)
log.Error().Err(err).Msg("wrong rego policy")
}

}
Expand All @@ -61,10 +61,11 @@ const (
type Input map[string]interface{}

func checkAuthorization(authorizationHeader string) (string, bool) {

log.Debug().Msg("Check authorization")
parts := strings.Split(authorizationHeader, " ")
if len(parts) < 2 {
return "", false
log.Debug().Msg("No authorizationHeader")
return "", false
}
if strings.ToLower(parts[0]) == "bearer" {
if len(core.AppConfig.ApiKeys) > 0 {
Expand Down Expand Up @@ -102,6 +103,7 @@ func checkAuthorization(authorizationHeader string) (string, bool) {
}
user := tokenParts[0]
password := tokenParts[1]
log.Debug().Str("user",user).Str("password",password).Msg("Basic authentication found")
// Check staff user
if core.AppConfig.StaffUser != "" && user == core.AppConfig.StaffUser {
if password == core.AppConfig.StaffPassword {
Expand Down Expand Up @@ -186,9 +188,9 @@ func checkPolicy(c echo.Context) Action {
}

// extract input from request
authorization := req.Header.Get(core.AppConfig.AuthorizationHeader)
authorization := req.Header.Get("Authorization")
role, authorized := checkAuthorization(authorization)
if !authorized && core.AppConfig.OpaSvc == "" && core.AppConfig.Policy == "" && (core.AppConfig.ParticipantUser != "" || core.AppConfig.StaffUser != "") {
if !authorized && (core.AppConfig.OpaSvc != "" || core.AppConfig.Policy != "") && (core.AppConfig.ParticipantUser != "" || core.AppConfig.StaffUser != "") {
log.Debug().Str("authorization", authorization).Msg("Authorization failed")
return Authorize
}
Expand Down

0 comments on commit 0b3c0e5

Please sign in to comment.