Compare commits

..

No commits in common. "main" and "v0.3.6" have entirely different histories.
main ... v0.3.6

10 changed files with 74 additions and 144 deletions

View file

@ -2,7 +2,6 @@ package cmd
import ( import (
opaal "davidallendj/opaal/internal" opaal "davidallendj/opaal/internal"
"davidallendj/opaal/internal/oidc"
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
@ -10,13 +9,9 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var ( var exampleCmd = &cobra.Command{
endpoints oidc.Endpoints
)
var serveCmd = &cobra.Command{
Use: "serve", Use: "serve",
Short: "Start an simple, bare minimal identity provider server", Short: "Start an simple identity provider server",
Long: "The built-in identity provider is not (nor meant to be) a complete OIDC implementation and behaves like an external IdP", Long: "The built-in identity provider is not (nor meant to be) a complete OIDC implementation and behaves like an external IdP",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
s := opaal.NewServerWithConfig(&config) s := opaal.NewServerWithConfig(&config)
@ -26,15 +21,11 @@ var serveCmd = &cobra.Command{
if errors.Is(err, http.ErrServerClosed) { if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("Identity provider server closed.\n") fmt.Printf("Identity provider server closed.\n")
} else if err != nil { } else if err != nil {
fmt.Printf("failed to start server: %v", err) fmt.Errorf("failed to start server: %v", err)
} }
}, },
} }
func init() { func init() {
serveCmd.Flags().StringVar(&endpoints.Authorization, "endpoints.authorization", "", "set the authorization endpoint for the identity provider") rootCmd.AddCommand(exampleCmd)
serveCmd.Flags().StringVar(&endpoints.Token, "endpoints.token", "", "set the token endpoint for the identity provider")
serveCmd.Flags().StringVar(&endpoints.JwksUri, "endpoints.jwks_uri", "", "set the JWKS endpoints for the identity provider")
rootCmd.AddCommand(serveCmd)
} }

View file

@ -2,7 +2,6 @@ package opaal
import ( import (
"davidallendj/opaal/internal/oauth" "davidallendj/opaal/internal/oauth"
"davidallendj/opaal/internal/oidc"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -73,18 +72,11 @@ type Config struct {
} }
func NewConfig() Config { func NewConfig() Config {
config := Config{ return Config{
Version: goutil.GetCommit(), Version: goutil.GetCommit(),
Server: server.Server{ Server: server.Server{
Host: "127.0.0.1", Host: "127.0.0.1",
Port: 3333, Port: 3333,
Issuer: server.IdentityProviderServer{
Endpoints: oidc.Endpoints{
Authorization: "",
Token: "",
JwksUri: "",
},
},
}, },
Options: Options{ Options: Options{
RunOnce: true, RunOnce: true,
@ -107,7 +99,6 @@ func NewConfig() Config {
}, },
}, },
} }
return config
} }
func LoadConfig(path string) Config { func LoadConfig(path string) Config {

View file

@ -51,9 +51,6 @@ func NewJwtBearerFlow(eps JwtBearerFlowEndpoints, params JwtBearerFlowParams) (s
if client == nil { if client == nil {
return "", fmt.Errorf("invalid client (client is nil)") return "", fmt.Errorf("invalid client (client is nil)")
} }
if verbose {
fmt.Printf("ID token (IDP): %s\n access token (IDP): %s", accessToken, idToken)
}
if accessToken != "" { if accessToken != "" {
_, err := jws.Verify([]byte(accessToken), jws.WithKeySet(client.Provider.KeySet), jws.WithValidateKey(true)) _, err := jws.Verify([]byte(accessToken), jws.WithKeySet(client.Provider.KeySet), jws.WithValidateKey(true))
if err != nil { if err != nil {

View file

@ -42,9 +42,8 @@ func Login(config *Config) error {
AuthProvider: &oidc.IdentityProvider{ AuthProvider: &oidc.IdentityProvider{
Issuer: config.Authorization.Endpoints.Issuer, Issuer: config.Authorization.Endpoints.Issuer,
Endpoints: oidc.Endpoints{ Endpoints: oidc.Endpoints{
Config: config.Authorization.Endpoints.Config, Config: config.Authorization.Endpoints.Config,
Authorization: config.Authorization.Endpoints.Authorize, JwksUri: config.Authorization.Endpoints.JwksUri,
JwksUri: config.Authorization.Endpoints.JwksUri,
}, },
}, },
JwtBearerEndpoints: flows.JwtBearerFlowEndpoints{ JwtBearerEndpoints: flows.JwtBearerFlowEndpoints{

View file

@ -90,11 +90,9 @@ func NewServerWithConfig(conf *Config) *server.Server {
}, },
Host: host, Host: host,
Port: port, Port: port,
Issuer: server.IdentityProviderServer{ Issuer: server.Issuer{
Host: conf.Server.Issuer.Host, Host: conf.Server.Issuer.Host,
Port: conf.Server.Issuer.Port, Port: conf.Server.Issuer.Port,
Endpoints: conf.Server.Issuer.Endpoints,
Clients: conf.Server.Issuer.Clients,
}, },
} }
return server return server

View file

@ -109,14 +109,12 @@ func (client *Client) FetchTokenFromAuthenticationServer(code string, state stri
} }
res, err := http.PostForm(client.Provider.Endpoints.Token, body) res, err := http.PostForm(client.Provider.Endpoints.Token, body)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get ID token: %v", err) return nil, fmt.Errorf("failed to get ID token: %s", err)
} }
b, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err)
}
fmt.Printf("%s\n", string(b))
defer res.Body.Close() defer res.Body.Close()
return b, nil // domain, _ := url.Parse("http://127.0.0.1")
// client.Jar.SetCookies(domain, res.Cookies())
return io.ReadAll(res.Body)
} }

View file

@ -164,25 +164,3 @@ func (p *IdentityProvider) FetchJwks() error {
return nil return nil
} }
func (p *IdentityProvider) UpdateEndpoints(other *IdentityProvider) {
UpdateEndpoints(&p.Endpoints, &other.Endpoints)
}
func UpdateEndpoints(eps *Endpoints, other *Endpoints) {
// only update endpoints that are not empty
var UpdateIfEmpty = func(ep *string, s string) {
if ep != nil {
if *ep == "" {
*ep = s
}
}
}
UpdateIfEmpty(&eps.Config, other.Config)
UpdateIfEmpty(&eps.Authorization, other.Authorization)
UpdateIfEmpty(&eps.Token, other.Token)
UpdateIfEmpty(&eps.Revocation, other.Revocation)
UpdateIfEmpty(&eps.Introspection, other.Introspection)
UpdateIfEmpty(&eps.UserInfo, other.UserInfo)
UpdateIfEmpty(&eps.JwksUri, other.JwksUri)
}

View file

@ -3,6 +3,7 @@ package server
import ( import (
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"davidallendj/opaal/internal/oauth"
"davidallendj/opaal/internal/oidc" "davidallendj/opaal/internal/oidc"
"encoding/json" "encoding/json"
"fmt" "fmt"
@ -21,22 +22,6 @@ import (
"github.com/lestrrat-go/jwx/v2/jwt" "github.com/lestrrat-go/jwx/v2/jwt"
) )
// TODO: make this a completely separate server
type IdentityProviderServer struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Endpoints oidc.Endpoints `yaml:"endpoints"`
Clients []RegisteredClient `yaml:"clients"`
}
// NOTE: could we use a oauth.Client here instead??
type RegisteredClient struct {
Id string `yaml:"id"`
Secret string `yaml:"secret"`
Name string `yaml:"name"`
RedirectUris []string `yaml:"redirect-uris"`
}
func (s *Server) StartIdentityProvider() error { func (s *Server) StartIdentityProvider() error {
// NOTE: this example does NOT implement CSRF tokens nor use them // NOTE: this example does NOT implement CSRF tokens nor use them
@ -44,16 +29,14 @@ func (s *Server) StartIdentityProvider() error {
var ( var (
r = chi.NewRouter() r = chi.NewRouter()
// clients = []oauth.Client{} // clients = []oauth.Client{}
callback = ""
activeCodes = []string{} activeCodes = []string{}
) )
// update endpoints that have values set // check if callback is set
defaultEps := oidc.Endpoints{ if s.Callback == "" {
Authorization: "http://" + s.Addr + "/oauth2/authorize", callback = "/oidc/callback"
Token: "http://" + s.Addr + "/oauth2/token",
JwksUri: "http://" + s.Addr + "/.well-known/jwks.json",
} }
oidc.UpdateEndpoints(&s.Issuer.Endpoints, &defaultEps)
// generate key pair used to sign JWKS and create JWTs // generate key pair used to sign JWKS and create JWTs
privateKey, err := rsa.GenerateKey(rand.Reader, 2048) privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
@ -89,13 +72,14 @@ func (s *Server) StartIdentityProvider() error {
w.Write(b) w.Write(b)
}) })
// TODO: create .well-known openid configuration
r.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { r.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
// create config JSON to serve with GET request // create config JSON to serve with GET request
config := map[string]any{ config := map[string]any{
"issuer": "http://" + s.Addr, "issuer": "http://" + s.Addr,
"authorization_endpoint": s.Issuer.Endpoints.Authorization, "authorization_endpoint": "http://" + s.Addr + "/oauth/authorize",
"token_endpoint": s.Issuer.Endpoints.Token, "token_endpoint": "http://" + s.Addr + "/oauth/token",
"jwks_uri": s.Issuer.Endpoints.JwksUri, "jwks_uri": "http://" + s.Addr + "/.well-known/jwks.json",
"scopes_supported": []string{ "scopes_supported": []string{
"openid", "openid",
"profile", "profile",
@ -147,18 +131,21 @@ func (s *Server) StartIdentityProvider() error {
username := r.Form.Get("username") username := r.Form.Get("username")
password := r.Form.Get("password") password := r.Form.Get("password")
if len(s.Issuer.Clients) <= 0 {
fmt.Printf("no registered clients found with identity provider (add them in config)\n")
return
}
// example username and password so do simplified authorization code flow // example username and password so do simplified authorization code flow
if username == "openchami" && password == "openchami" { if username == "ochami" && password == "ochami" {
client := s.Issuer.Clients[0] client := oauth.Client{
Id: "ochami",
Secret: "ochami",
Name: "ochami",
Provider: oidc.IdentityProvider{
Issuer: "http://127.0.0.1:3333",
},
RedirectUris: []string{fmt.Sprintf("http://%s:%d%s", s.Host, s.Port, callback)},
}
// check if there are any redirect URIs supplied // check if there are any redirect URIs supplied
if len(client.RedirectUris) <= 0 { if len(client.RedirectUris) <= 0 {
fmt.Printf("no redirect URIs found for client %s (ID: %s)\n", client.Name, client.Id) fmt.Printf("no redirect URIs found")
return return
} }
for _, url := range client.RedirectUris { for _, url := range client.RedirectUris {
@ -179,7 +166,7 @@ func (s *Server) StartIdentityProvider() error {
http.Redirect(w, r, "/browser/login", http.StatusUnauthorized) http.Redirect(w, r, "/browser/login", http.StatusUnauthorized)
} }
}) })
r.HandleFunc("/oauth2/token", func(w http.ResponseWriter, r *http.Request) { r.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm() r.ParseForm()
// check for authorization code and make sure it's valid // check for authorization code and make sure it's valid
@ -253,7 +240,7 @@ func (s *Server) StartIdentityProvider() error {
fmt.Printf("bearer: %s\n", string(b)) fmt.Printf("bearer: %s\n", string(b))
w.Write(b) w.Write(b)
}) })
r.HandleFunc("/oauth2/authorize", func(w http.ResponseWriter, r *http.Request) { r.HandleFunc("/oauth/authorize", func(w http.ResponseWriter, r *http.Request) {
var ( var (
responseType = r.URL.Query().Get("response_type") responseType = r.URL.Query().Get("response_type")
clientId = r.URL.Query().Get("client_id") clientId = r.URL.Query().Get("client_id")
@ -266,13 +253,9 @@ func (s *Server) StartIdentityProvider() error {
return return
} }
// find a valid client // check that we're using the default registered client
index := slices.IndexFunc(s.Issuer.Clients, func(c RegisteredClient) bool { if clientId != "ochami" {
fmt.Printf("%s ? %s\n", c.Id, clientId) fmt.Printf("invalid client\n")
return c.Id == clientId
})
if index < 0 {
fmt.Printf("no valid client found")
return return
} }

View file

@ -18,11 +18,16 @@ import (
type Server struct { type Server struct {
*http.Server *http.Server
Host string `yaml:"host"` Host string `yaml:"host"`
Port int `yaml:"port"` Port int `yaml:"port"`
Callback string `yaml:"callback"` Callback string `yaml:"callback"`
State string `yaml:"state"` State string `yaml:"state"`
Issuer IdentityProviderServer `yaml:"issuer"` Issuer Issuer `yaml:"issuer"`
}
type Issuer struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} }
type ServerParams struct { type ServerParams struct {
@ -57,7 +62,7 @@ func (s *Server) StartLogin(clients []oauth.Client, params ServerParams) error {
// make the login page SSO buttons and authorization URLs to write to stdout // make the login page SSO buttons and authorization URLs to write to stdout
buttons := "" buttons := ""
fmt.Printf("Login with an identity provider: \n") fmt.Printf("Login with external identity providers: \n")
for i, client := range clients { for i, client := range clients {
// fetch provider configuration before adding button // fetch provider configuration before adding button
p, err := oidc.FetchServerConfig(client.Provider.Issuer) p, err := oidc.FetchServerConfig(client.Provider.Issuer)
@ -74,7 +79,8 @@ func (s *Server) StartLogin(clients []oauth.Client, params ServerParams) error {
clients[i].Provider = *p clients[i].Provider = *p
buttons += makeButton(fmt.Sprintf("/login?sso=%s", client.Id), client.Name) buttons += makeButton(fmt.Sprintf("/login?sso=%s", client.Id), client.Name)
fmt.Printf("\t%s: /login?sso=%s\n", client.Name, client.Id) url := client.BuildAuthorizationUrl(s.State)
fmt.Printf("\t%s\n", url)
} }
var code string var code string
@ -114,9 +120,7 @@ func (s *Server) StartLogin(clients []oauth.Client, params ServerParams) error {
client = &clients[index] client = &clients[index]
url := client.BuildAuthorizationUrl(s.State) url := client.BuildAuthorizationUrl(s.State)
if params.Verbose { fmt.Printf("Redirect URL: %s\n", url)
fmt.Printf("Redirect URL: %s\n", url)
}
http.Redirect(w, r, url, http.StatusFound) http.Redirect(w, r, url, http.StatusFound)
return return
} }
@ -141,47 +145,38 @@ func (s *Server) StartLogin(clients []oauth.Client, params ServerParams) error {
p = params.AuthProvider p = params.AuthProvider
jwks []byte jwks []byte
) )
// try and get the JWKS from param first
fetchAndMarshal := func() (err error) { if p.Endpoints.JwksUri != "" {
err = p.FetchJwks() err := p.FetchJwks()
if err != nil { if err != nil {
fmt.Printf("failed to fetch keys: %v\n", err) fmt.Printf("failed to fetch keys using JWKS url...trying to fetch config and try again...\n")
return
} }
jwks, err = json.Marshal(p.KeySet) jwks, err = json.Marshal(p.KeySet)
if err != nil { if err != nil {
fmt.Printf("failed to marshal JWKS: %v\n", err) fmt.Printf("failed to marshal JWKS: %v\n", err)
} }
return } else if p.Endpoints.Config != "" && jwks == nil {
} // otherwise, try and fetch the whole config and try again
err := p.FetchServerConfig()
// try and get the JWKS from param first if err != nil {
if p.Endpoints.JwksUri != "" {
if err := fetchAndMarshal(); err != nil {
w.Write(jwks)
return
}
}
// otherwise or if fetching the JWKS failed, try and fetch the whole config first and try again
if p.Endpoints.Config != "" {
if err := p.FetchServerConfig(); err != nil {
fmt.Printf("failed to fetch server config: %v\n", err) fmt.Printf("failed to fetch server config: %v\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Redirect(w, r, "/error", http.StatusInternalServerError)
return
}
err = p.FetchJwks()
if err != nil {
fmt.Printf("failed to fetch JWKS after fetching server config: %v\n", err)
http.Redirect(w, r, "/error", http.StatusInternalServerError)
return return
} }
} else {
fmt.Printf("getting JWKS from param failed and endpoints config unavailable\n")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
} }
if err := fetchAndMarshal(); err != nil { // forward the JWKS from the authorization server
fmt.Printf("failed to fetch and marshal JWKS after config update: %v\n", err) if jwks == nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) fmt.Printf("no JWKS was fetched from authorization server\n")
http.Redirect(w, r, "/error", http.StatusInternalServerError)
return return
} }
w.Write(jwks) w.Write(jwks)
}) })
r.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { r.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {

View file

@ -7,7 +7,7 @@
<input type="password" id="password" name="password" title="password" placeholder="Enter your password..." /><br/> <input type="password" id="password" name="password" title="password" placeholder="Enter your password..." /><br/>
<button type="submit" class="btn">Login</button><br/> <button type="submit" class="btn">Login</button><br/>
<a class="forgot" href="#">Forgot Username?</a><br/> <a class="forgot" href="#">Forgot Username?</a><br/>
<label>(hint: try 'openchami' for both username and password)</label> <label>(hint: try 'ochami' for both username and password)</label>
</form> </form>
</div><!--end log form --> </div><!--end log form -->
</html> </html>