Refactored, reorganized, fixed issues, and implemented functionality

This commit is contained in:
David Allen 2024-02-24 00:26:51 -07:00
parent 3edc5e1191
commit 5428085fdf
No known key found for this signature in database
GPG key ID: 1D2A29322FBB6FCB
9 changed files with 524 additions and 190 deletions

View file

@ -1,99 +1,13 @@
package cmd
import (
"davidallendj/opaal/internal/oauth"
"davidallendj/opaal/internal/oidc"
opaal "davidallendj/opaal/internal"
"davidallendj/opaal/internal/util"
"fmt"
"log"
"os"
"path/filepath"
"github.com/spf13/cobra"
yaml "gopkg.in/yaml.v2"
)
type Server struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type AuthEndpoints struct {
Identities string `yaml:"identities"`
TrustedIssuers string `yaml:"trusted-issuers"`
AccessToken string `yaml:"access-token"`
ServerConfig string `yaml:"server-config"`
}
type Config struct {
Server Server `yaml:"server"`
Client oauth.Client `yaml:"client"`
IdentityProvider oidc.IdentityProvider `yaml:"oidc"`
State string `yaml:"state"`
ResponseType string `yaml:"response-type"`
Scope []string `yaml:"scope"`
AuthEndpoints AuthEndpoints `yaml:"urls"`
OpenBrowser bool `yaml:"open-browser"`
}
func NewConfig() Config {
return Config{
Server: Server{
Host: "127.0.0.1",
Port: 3333,
},
Client: oauth.Client{
Id: "",
Secret: "",
RedirectUris: []string{""},
},
IdentityProvider: *oidc.NewIdentityProvider(),
State: util.RandomString(20),
ResponseType: "code",
Scope: []string{"openid", "profile", "email"},
AuthEndpoints: AuthEndpoints{
Identities: "",
AccessToken: "",
TrustedIssuers: "",
ServerConfig: "",
},
OpenBrowser: false,
}
}
func LoadConfig(path string) Config {
var c Config = NewConfig()
file, err := os.ReadFile(path)
if err != nil {
log.Printf("failed to read config file: %v\n", err)
return c
}
err = yaml.Unmarshal(file, &c)
if err != nil {
log.Fatalf("failed to unmarshal config: %v\n", err)
return c
}
return c
}
func SaveDefaultConfig(path string) {
path = filepath.Clean(path)
if path == "" || path == "." {
path = "config.yaml"
}
var c = NewConfig()
data, err := yaml.Marshal(c)
if err != nil {
log.Printf("failed to marshal config: %v\n", err)
return
}
err = os.WriteFile(path, data, os.ModePerm)
if err != nil {
log.Printf("failed to write default config file: %v\n", err)
return
}
}
var configCmd = &cobra.Command{
Use: "config",
Short: "Create a new default config file",
@ -105,7 +19,7 @@ var configCmd = &cobra.Command{
fmt.Printf("file or directory exists\n")
continue
}
SaveDefaultConfig(path)
opaal.SaveDefaultConfig(path)
}
},
}

View file

@ -1,22 +1,14 @@
package cmd
import (
"davidallendj/opal/internal/api"
"davidallendj/opal/internal/oidc"
"davidallendj/opal/internal/util"
"encoding/json"
"errors"
opaal "davidallendj/opaal/internal"
"davidallendj/opaal/internal/util"
"fmt"
"net/http"
"os"
"github.com/spf13/cobra"
)
func hasRequiredParams(config *Config) bool {
return config.Client.Id != "" && config.Client.Secret != ""
}
var loginCmd = &cobra.Command{
Use: "login",
Short: "Start the login flow",
@ -28,95 +20,15 @@ var loginCmd = &cobra.Command{
fmt.Printf("failed to load config")
os.Exit(1)
} else if exists {
config = LoadConfig(configPath)
config = opaal.LoadConfig(configPath)
} else {
config = NewConfig()
config = opaal.NewConfig()
}
}
// try and fetch server configuration if provided URL
idp := oidc.NewIdentityProvider()
if config.AuthEndpoints.ServerConfig != "" {
idp.FetchServerConfig(config.AuthEndpoints.ServerConfig)
} else {
// otherwise, use what's provided in config file
idp.Issuer = config.IdentityProvider.Issuer
idp.Endpoints = config.IdentityProvider.Endpoints
idp.Supported = config.IdentityProvider.Supported
}
// check if all appropriate parameters are set in config
if !hasRequiredParams(&config) {
fmt.Printf("client ID must be set\n")
os.Exit(1)
}
// build the authorization URL to redirect user for social sign-in
var authorizationUrl = util.BuildAuthorizationUrl(
idp.Endpoints.Authorize,
config.Client.Id,
config.Client.RedirectUris,
config.State,
config.ResponseType,
config.Scope,
)
// print the authorization URL for sharing
serverAddr := fmt.Sprintf("%s:%d", config.IdentityProvider.Issuer)
fmt.Printf(`Login with identity provider:
%s/login
%s\n`,
serverAddr, authorizationUrl,
)
// automatically open browser to initiate login flow (only useful for testing)
if config.OpenBrowser {
util.OpenUrl(authorizationUrl)
}
// authorize oauth client and listen for callback from provider
fmt.Printf("Waiting for authorization code redirect @%s/oidc/callback...\n", serverAddr)
code, err := api.WaitForAuthorizationCode(serverAddr, authorizationUrl)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("Server closed.\n")
} else if err != nil {
fmt.Printf("Error starting server: %s\n", err)
os.Exit(1)
}
// use code from response and exchange for bearer token (with ID token)
tokenString, err := api.FetchIssuerToken(
code,
idp.Endpoints.Token,
config.Client,
config.State,
)
err := opaal.Login(&config)
if err != nil {
fmt.Printf("%v\n", err)
return
}
// extract ID token from bearer as JSON string for easy consumption
var data map[string]any
json.Unmarshal([]byte(tokenString), &data)
idToken := data["id_token"].(string)
// create a new identity with identity and session manager if url is provided
if config.AuthEndpoints.Identities != "" {
api.CreateIdentity(config.AuthEndpoints.Identities, idToken)
api.FetchIdentities(config.AuthEndpoints.Identities)
}
// fetch JWKS and add issuer to authentication server to submit ID token
err = idp.FetchJwk("")
if err != nil {
fmt.Printf("failed to fetch JWK: %v\n", err)
} else {
api.AddTrustedIssuer(config.AuthEndpoints.TrustedIssuers, idp.Key)
}
// use ID token/user info to fetch access token from authentication server
if config.AuthEndpoints.AccessToken != "" {
api.FetchAccessToken(config.AuthEndpoints.AccessToken, config.Client.Id, idToken, config.Scope)
fmt.Print(err)
os.Exit(1)
}
},
}
@ -131,5 +43,7 @@ func init() {
loginCmd.Flags().StringVar(&config.Server.Host, "host", config.Server.Host, "set the listening host")
loginCmd.Flags().IntVar(&config.Server.Port, "port", config.Server.Port, "set the listening port")
loginCmd.Flags().BoolVar(&config.OpenBrowser, "open-browser", config.OpenBrowser, "automatically open link in browser")
loginCmd.Flags().BoolVar(&config.DecodeIdToken, "decode-id-token", config.DecodeIdToken, "decode and print ID token from identity provider")
loginCmd.Flags().BoolVar(&config.DecodeAccessToken, "decore-access-token", config.DecodeAccessToken, "decode and print access token from authorization server")
rootCmd.AddCommand(loginCmd)
}

View file

@ -1,6 +1,7 @@
package cmd
import (
opaal "davidallendj/opaal/internal"
"fmt"
"os"
@ -9,7 +10,7 @@ import (
var (
configPath = ""
config Config
config opaal.Config
)
var rootCmd = &cobra.Command{
Use: "oidc",