Refactored and reorganized code

This commit is contained in:
David Allen 2024-02-23 16:06:07 -07:00
parent 86f8784c19
commit fdb0db389c
8 changed files with 384 additions and 127 deletions

View file

@ -2,40 +2,65 @@ package api
import (
"bytes"
"davidallendj/opal/internal/oauth"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
func WaitForAuthorizationCode(host string, port int) (string, error) {
func WaitForAuthorizationCode(serverAddr string, loginUrl string) (string, error) {
var code string
s := &http.Server{
Addr: fmt.Sprintf("%s:%d", host, port),
}
s := &http.Server{Addr: serverAddr}
http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
// redirect directly to identity provider with this endpoint
http.Redirect(w, r, loginUrl, http.StatusSeeOther)
})
http.HandleFunc("/oidc/callback", func(w http.ResponseWriter, r *http.Request) {
// get the code from the OIDC provider
if r != nil {
code = r.URL.Query().Get("code")
fmt.Printf("authorization code: %v\n", code)
fmt.Printf("Authorization code: %v\n", code)
}
s.Close()
})
fmt.Printf("listening for authorization code at %s/oidc/callback\n", s.Addr)
return code, s.ListenAndServe()
}
func FetchToken(code string, remoteUrl string, clientId string, clientSecret string, state string, redirectUri []string) (string, error) {
func FetchIssuerToken(code string, remoteUrl string, client oauth.Client, state string) (string, error) {
var token string
data := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"client_id": {clientId},
"client_secret": {clientSecret},
"client_id": {client.Id},
"client_secret": {client.Secret},
"state": {state},
"redirect_uri": {strings.Join(redirectUri, ",")},
"redirect_uri": {strings.Join(client.RedirectUris, ",")},
}
res, err := http.PostForm(remoteUrl, data)
if err != nil {
return "", fmt.Errorf("failed to get ID token: %s", err)
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return "", fmt.Errorf("failed to read response body: %v", err)
}
token = string(b)
fmt.Printf("%v\n", token)
return token, nil
}
func FetchAccessToken(remoteUrl string, clientId string, jwt string, scopes []string) (string, error) {
// hydra endpoint: /oauth/token
var token string
data := url.Values{
"grant_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
"assertion": {jwt},
}
res, err := http.PostForm(remoteUrl, data)
if err != nil {
@ -53,31 +78,34 @@ func FetchToken(code string, remoteUrl string, clientId string, clientSecret str
return token, nil
}
func FetchAccessToken(remoteUrl string, clientId string, jwt string) (string, error) {
var token string
data := url.Values{
"grant_type": {"client_credentials"},
"client_id": {clientId},
"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
"client_assertion": {jwt},
}
res, err := http.PostForm(remoteUrl, data)
if err != nil {
return "", fmt.Errorf("failed to get token: %s", err)
}
defer res.Body.Close()
func AddTrustedIssuer(remoteUrl string, issuer string, subject string, duration time.Duration, jwk string, scope []string) error {
// hydra endpoint: /admin/trust/grants/jwt-bearer/issuers
data := []byte(fmt.Sprintf(`{
"allow_any_subject": false,
"issuer": "%s",
"subject": "%s"
"expires_at": "%v"
"jwk": %v,
"scope": [ j%s ],
}`, issuer, subject, time.Now().Add(duration), jwk, strings.Join(scope, ",")))
b, err := io.ReadAll(res.Body)
req, err := http.NewRequest("POST", remoteUrl, bytes.NewBuffer(data))
if err != nil {
return "", fmt.Errorf("failed to read response body: %v", err)
return fmt.Errorf("failed to create a new request: %v", err)
}
token = string(b)
fmt.Printf("%v\n", token)
return token, nil
req.Header.Add("Content-Type", "application/json")
// req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", idToken))
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to do request: %v", err)
}
fmt.Printf("%d\n", res.StatusCode)
return nil
}
func CreateIdentity(remoteUrl string, idToken string) error {
// kratos endpoint: /admin/identities
data := []byte(`{
"schema_id": "preset://email",
"traits": {
@ -114,3 +142,7 @@ func FetchIdentities(remoteUrl string) error {
fmt.Printf("%v\n", res)
return nil
}
func RedirectSuccess() {
// show a success page with the user's access token
}

View file

@ -1,15 +1,15 @@
package oauth
type Client struct {
Id string
Secret string
Issuer string
Id string `yaml:"id"`
Secret string `yaml:"secret"`
RedirectUris []string `yaml:"redirect_uris"`
}
func NewClient() *Client {
return &Client{
Id: "",
Secret: "",
Issuer: "",
Id: "",
Secret: "",
RedirectUris: []string{""},
}
}

View file

@ -1,38 +1,100 @@
package oidc
import "fmt"
import (
"context"
"fmt"
type OpenIDConnectProvider struct {
Host string
Port int
AuthorizeEndpoint string
TokenEndpoint string
ConfigEndpoint string
"github.com/lestrrat-go/jwx/jwk"
)
type IdentityProvider struct {
Issuer string `json:"issuer" yaml:"issuer"`
Endpoints Endpoints `json:"endpoints" yaml:"endpoints"`
Supported Supported `json:"supported" yaml:"supported"`
Key jwk.Key
}
func NewOIDCProvider() *OpenIDConnectProvider {
return &OpenIDConnectProvider{
Host: "127.0.0.1",
Port: 80,
AuthorizeEndpoint: "/oauth/authorize",
TokenEndpoint: "/oauth/token",
type Endpoints struct {
Authorize string `json:"authorize_endpoint" yaml:"authorize"`
Token string `json:"token_endpoint" yaml:"token"`
Revocation string `json:"revocation_endpoint" yaml:"revocation"`
Introspection string `json:"introspection_endpoint" yaml:"introspection"`
UserInfo string `json:"userinfo_endpoint" yaml:"userinfo"`
Jwks string `json:"jwks_uri" yaml:"jwks_uri"`
}
type Supported struct {
ResponseTypes []string `json:"response_types_supported"`
ResponseModes []string `json:"response_modes_supported"`
GrantTypes []string `json:"grant_types_supported"`
TokenEndpointAuthMethods []string `json:"token_endpoint_auth_methods_supported"`
SubjectTypes []string `json:"subject_types_supported"`
IdTokenSigningAlgValues []string `json:"id_token_signing_alg_values_supported"`
ClaimTypes []string `json:"claim_types_supported"`
Claims []string `json:"claims_supported"`
}
func NewIdentityProvider() *IdentityProvider {
p := &IdentityProvider{Issuer: "127.0.0.1"}
p.Endpoints = Endpoints{
Authorize: p.Issuer + "/oauth/authorize",
Token: p.Issuer + "/oauth/token",
Revocation: p.Issuer + "/oauth/revocation",
Introspection: p.Issuer + "/oauth/introspect",
UserInfo: p.Issuer + "/oauth/userinfo",
Jwks: p.Issuer + "/oauth/discovery/keys",
}
}
func (oidc *OpenIDConnectProvider) GetAuthorizeUrl() string {
if oidc.Port != 80 {
return fmt.Sprintf("%s:%d", oidc.Host, oidc.Port) + oidc.AuthorizeEndpoint
p.Supported = Supported{
ResponseTypes: []string{"code"},
ResponseModes: []string{"query"},
GrantTypes: []string{
"authorization_code",
"client_credentials",
"refresh_token",
},
TokenEndpointAuthMethods: []string{
"client_secret_basic",
"client_secret_post",
},
SubjectTypes: []string{"public"},
IdTokenSigningAlgValues: []string{"RS256"},
ClaimTypes: []string{"normal"},
Claims: []string{
"iss",
"sub",
"aud",
"exp",
"iat",
},
}
return oidc.Host + oidc.AuthorizeEndpoint
return p
}
func (oidc *OpenIDConnectProvider) GetTokenUrl() string {
if oidc.Port != 80 {
return fmt.Sprintf("%s:%d", oidc.Host, oidc.Port) + oidc.TokenEndpoint
}
return oidc.Host + oidc.TokenEndpoint
}
func (oidc *OpenIDConnectProvider) FetchServerConfiguration(url string) {
func (p *IdentityProvider) FetchServerConfig(url string) {
// make a request to a server's openid-configuration
}
func (p *IdentityProvider) FetchJwk(url string) error {
//
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
set, err := jwk.Fetch(ctx, url)
if err != nil {
return fmt.Errorf("%v", err)
}
// get the first JWK from set
for it := set.Iterate(context.Background()); it.Next(context.Background()); {
pair := it.Pair()
p.Key = pair.Value.(jwk.Key)
return nil
}
return fmt.Errorf("failed to load public key: %v", err)
}
func (p *IdentityProvider) GetRawJwk() (any, error) {
var rawkey any
if err := p.Key.Raw(&rawkey); err != nil {
return nil, fmt.Errorf("failed to get raw key: %v", err)
}
return rawkey, nil
}

View file

@ -5,6 +5,8 @@ import (
"math/rand"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
)
@ -58,3 +60,22 @@ func PathExists(path string) (bool, error) {
}
return false, err
}
// https://stackoverflow.com/questions/39320371/how-start-web-server-to-open-page-in-browser-in-golang
// open opens the specified URL in the default browser of the user.
func OpenUrl(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}