Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

chore: modernize code #378

Merged
merged 18 commits into from
Dec 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ coverage:
ignore:
- "docs/**/*"
- "tests/**/*"
- "internal/utils/testutils/*"
- "pkg/**/*"
- "wiki/**/*"
24 changes: 0 additions & 24 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,6 @@ jobs:
- run: go test ./... -timeout 20s -race -covermode=atomic -coverprofile=coverage.out -coverpkg=./...
- run: go test ./... -timeout 20s -bench . -benchmem -count 3

- name: Install build dependencies
run: |
sudo dpkg --add-architecture arm64
sudo sed -i'' -E 's/^(deb|deb-src) /\1 [arch=amd64,i386] /' /etc/apt/sources.list

echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ $(lsb_release -cs) main restricted universe" | sudo tee /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ $(lsb_release -cs)-updates main restricted universe" | sudo tee -a /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ $(lsb_release -cs)-security main restricted universe" | sudo tee -a /etc/apt/sources.list.d/arm64.list

sudo apt-get update -q
sudo apt-get install --no-install-recommends -qy $PACKAGES

- name: Write gpg sign key
if: env.GPG_KEY != null
run: echo "$GPG_KEY" > "$GPG_KEY_PATH"
Expand Down Expand Up @@ -93,18 +81,6 @@ jobs:
permissions:
contents: write
steps:
- name: Install build dependencies
run: |
sudo dpkg --add-architecture arm64
sudo sed -i'' -E 's/^(deb|deb-src) /\1 [arch=amd64,i386] /' /etc/apt/sources.list

echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ $(lsb_release -cs) main restricted universe" | sudo tee /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ $(lsb_release -cs)-updates main restricted universe" | sudo tee -a /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ $(lsb_release -cs)-security main restricted universe" | sudo tee -a /etc/apt/sources.list.d/arm64.list

sudo apt-get update -q
sudo apt-get install --no-install-recommends -qy $PACKAGES

- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0
Expand Down
2 changes: 1 addition & 1 deletion .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ linters-settings:
revive:
rules:
- name: argument-limit
arguments: [ 6 ]
arguments: [ 7 ]
- name: atomic
- name: bare-return
- name: blank-imports
Expand Down
18 changes: 0 additions & 18 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,6 @@ builds:
- -trimpath
ldflags:
- -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}} -X main.builtBy=goreleaser
- id: "openvpn-auth-oauth2.so"
binary: openvpn-auth-oauth2
main: ./pkg/plugin/
buildmode: c-shared
goos:
- linux
goarch:
- amd64
- arm64
mod_timestamp: '{{ .CommitTimestamp }}'
env:
- CGO_ENABLED=1
- >-
{{- if eq .Arch "amd64"}}CC=x86_64-linux-gnu-gcc{{- end }}
{{- if eq .Arch "arm64"}}CC=aarch64-linux-gnu-gcc{{- end }}
- >-
{{- if eq .Arch "amd64"}}CXX=x86_64-linux-gnu-g++{{- end }}
{{- if eq .Arch "arm64"}}CXX=aarch64-linux-gnu-g++{{- end }}

archives:
- id: openvpn-auth-oauth2
Expand Down
98 changes: 64 additions & 34 deletions cmd/daemon/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,64 +16,77 @@ import (
"syscall"

"github.com/jkroepke/openvpn-auth-oauth2/internal/config"
"github.com/jkroepke/openvpn-auth-oauth2/internal/httphandler"
"github.com/jkroepke/openvpn-auth-oauth2/internal/httpserver"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2/providers/generic"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2/providers/github"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2/providers/google"
"github.com/jkroepke/openvpn-auth-oauth2/internal/openvpn"
"github.com/jkroepke/openvpn-auth-oauth2/internal/storage"
"github.com/jkroepke/openvpn-auth-oauth2/internal/tokenstorage"
"github.com/jkroepke/openvpn-auth-oauth2/internal/utils"
)

// Execute runs the main program logic of openvpn-auth-oauth2.
//
//nolint:cyclop
func Execute(args []string, logWriter io.Writer, version, commit, date string) int {
var err error

logger := defaultLogger(logWriter)

flagSet := config.FlagSet(args[0])
flagSet.SetOutput(logWriter)

if err = flagSet.Parse(args[1:]); err != nil {
conf, err := configure(args, logWriter, version, commit, date)
if err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}

logger.Error(fmt.Errorf("error parsing cli args: %w", err).Error())
_, _ = fmt.Fprintln(logWriter, err.Error())

return 1
}

if flagSet.Lookup("version").Value.String() == "true" {
_, _ = fmt.Fprintf(logWriter, "version: %s\ncommit: %s\ndate: %s\ngo: %s\n", version, commit, date, runtime.Version())
logger, err := configureLogger(conf, logWriter)
if err != nil {
_, _ = fmt.Fprintln(logWriter, fmt.Errorf("error configure logging: %w", err).Error())

return 0
return 1
}

ctx, cancel := context.WithCancelCause(context.Background())
defer cancel(nil)

httpClient := &http.Client{Transport: utils.NewUserAgentTransport(http.DefaultTransport)}
tokenStorage := tokenstorage.NewInMemory(ctx, conf.OAuth2.Refresh.Secret.String(), conf.OAuth2.Refresh.Expires)

var provider oauth2.Provider

switch conf.OAuth2.Provider {
case generic.Name:
provider, err = generic.NewProvider(ctx, conf, httpClient)
case github.Name:
provider, err = github.NewProvider(ctx, conf, httpClient)
case google.Name:
provider, err = google.NewProvider(ctx, conf, httpClient)
default:
err = errors.New("unknown oauth2 provider: " + conf.OAuth2.Provider)
}

conf, err := config.Load(config.ManagementClient, flagSet.Lookup("config").Value.String(), flagSet)
if err != nil {
logger.Error(fmt.Errorf("error loading config: %w", err).Error())
logger.Error(err.Error())

return 1
}

logger, err = configureLogger(conf, logWriter)
openvpnClient := openvpn.New(logger, conf)

oAuth2Client, err := oauth2.New(ctx, logger, conf, httpClient, tokenStorage, provider, openvpnClient)
if err != nil {
logger = defaultLogger(logWriter)
logger.Error(fmt.Errorf("error configure logging: %w", err).Error())
logger.Error(err.Error())

return 1
}

ctx, cancel := context.WithCancelCause(context.Background())
defer cancel(nil)

httpClient := &http.Client{Transport: utils.NewUserAgentTransport(http.DefaultTransport)}
storageClient := storage.New(ctx, conf.OAuth2.Refresh.Secret.String(), conf.OAuth2.Refresh.Expires)
oauth2Client := oauth2.New(logger, conf, storageClient, httpClient)
openvpnClient := openvpn.New(ctx, logger, conf, oauth2Client)
openvpnClient.SetOAuth2Client(oAuth2Client)

if err = oauth2Client.Initialize(ctx, openvpnClient); err != nil {
httpHandler, err := httphandler.New(conf, oAuth2Client)
if err != nil {
logger.Error(err.Error())

return 1
Expand All @@ -92,7 +105,7 @@ func Execute(args []string, logWriter io.Writer, version, commit, date string) i
}()
}

server := httpserver.NewHTTPServer(httpserver.ServerNameDefault, logger, conf.HTTP, oauth2Client.Handler())
server := httpserver.NewHTTPServer(httpserver.ServerNameDefault, logger, conf.HTTP, httpHandler)

wg.Add(1)

Expand All @@ -113,7 +126,7 @@ func Execute(args []string, logWriter io.Writer, version, commit, date string) i
go func() {
defer wg.Done()

if err := openvpnClient.Connect(); err != nil {
if err := openvpnClient.Connect(context.Background()); err != nil {
cancel(fmt.Errorf("openvpn: %w", err))

return
Expand All @@ -125,8 +138,8 @@ func Execute(args []string, logWriter io.Writer, version, commit, date string) i
termCh := make(chan os.Signal, 1)
signal.Notify(termCh, os.Interrupt, syscall.SIGHUP, syscall.SIGTERM)

logger.Info(
"openvpn-auth-oauth2 started with base url " + conf.HTTP.BaseURL.String(),
logger.LogAttrs(ctx, slog.LevelInfo,
"openvpn-auth-oauth2 started with base url "+conf.HTTP.BaseURL.String(),
)

for {
Expand Down Expand Up @@ -177,10 +190,27 @@ func setupDebugListener(ctx context.Context, logger *slog.Logger, conf config.Co
return nil
}

func defaultLogger(writer io.Writer) *slog.Logger {
return slog.New(slog.NewTextHandler(writer, &slog.HandlerOptions{
AddSource: false,
}))
// configure parses the command line arguments and loads the configuration.
func configure(args []string, logWriter io.Writer, version, commit, date string) (config.Config, error) {
flagSet := config.FlagSet(args[0])
flagSet.SetOutput(logWriter)

if err := flagSet.Parse(args[1:]); err != nil {
return config.Config{}, fmt.Errorf("error parsing cli args: %w", err)
}

if flagSet.Lookup("version").Value.String() == "true" {
_, _ = fmt.Fprintf(logWriter, "version: %s\ncommit: %s\ndate: %s\ngo: %s\n", version, commit, date, runtime.Version())

return config.Config{}, flag.ErrHelp
}

conf, err := config.Load(config.ManagementClient, flagSet.Lookup("config").Value.String(), flagSet)
if err != nil {
return config.Config{}, fmt.Errorf("error loading config: %w", err)
}

return conf, nil
}

func configureLogger(conf config.Config, writer io.Writer) (*slog.Logger, error) {
Expand Down
4 changes: 2 additions & 2 deletions cmd/daemon/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ func TestExecuteConfigInvalid(t *testing.T) {
{
"invalid log level",
[]string{"", "--config=../../config.example.yaml", "--log.format=console", "--log.level=invalid", "--http.secret=" + testutils.Secret, "--http.listen=127.0.0.1:0"},
`error parsing cli args: invalid value \"invalid\" for flag -log.level: slog: level string \"invalid\": unknown name`,
`invalid value "invalid" for flag -log.level: slog: level string "invalid": unknown name`,
},
{
"error oidc provider",
[]string{"", "--config=../../config.example.yaml", "--log.format=console", "--log.level=info", "--http.secret=" + testutils.Secret, "--http.listen=127.0.0.1:0"},
`error oauth2 provider`,
`error oidc provider`,
},
{
"error http listener",
Expand Down
8 changes: 0 additions & 8 deletions go.work

This file was deleted.

Loading
Loading