Skip to content
Closed
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
7 changes: 6 additions & 1 deletion cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,12 +304,17 @@ func oauth2login(
completionChan <- ""
}

// Use a private mux so that several logins in the same process do not
// register the callback twice on the global http.DefaultServeMux.
mux := http.NewServeMux()
mux.HandleFunc("/auth/callback", callbackHandler)

// G112: Set ReadHeaderTimeout to mitigate Slowloris DoS attack.
srv := &http.Server{
Addr: "localhost:" + strconv.Itoa(port),
Handler: mux,
ReadHeaderTimeout: 3 * time.Second,
}
http.HandleFunc("/auth/callback", callbackHandler)

var url string
opts := []oauth2.AuthCodeOption{}
Expand Down
51 changes: 51 additions & 0 deletions cmd/logout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,64 @@
package cmd

import (
"context"
"fmt"
"net"
"net/http"
"path/filepath"
"testing"
"time"

"github.com/microcks/microcks-cli/pkg/config"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
)

func runOAuth2LoginWithError(t *testing.T) {
t.Helper()
l, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
port := l.Addr().(*net.TCPAddr).Port
require.NoError(t, l.Close())

oauth2conf := &oauth2.Config{
Endpoint: oauth2.Endpoint{
AuthURL: "http://127.0.0.1/auth",
TokenURL: "http://127.0.0.1/token",
},
}

done := make(chan error, 1)
go func() {
_, _, err := oauth2login(context.Background(), port, oauth2conf, false)
done <- err
}()

// Send an error callback so the login flow ends.
callbackURL := fmt.Sprintf("http://localhost:%d/auth/callback?error=access_denied", port)
require.Eventually(t, func() bool {
resp, err := http.Get(callbackURL) // #nosec G107 -- local test server
if err != nil {
return false
}
resp.Body.Close()
return true
}, 10*time.Second, 100*time.Millisecond)

select {
case err := <-done:
require.Error(t, err)
case <-time.After(10 * time.Second):
t.Fatal("oauth2login did not return")
}
}

func TestOAuth2LoginCanRunTwice(t *testing.T) {
runOAuth2LoginWithError(t)
// The second login must not panic on a duplicate callback registration.
runOAuth2LoginWithError(t)
}

func TestLogoutContextResolvesNamedContextUser(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config")
server := "https://microcks.example"
Expand Down
Loading