Major refactoring and code restructure

This commit is contained in:
David Allen 2024-03-10 20:19:29 -06:00
parent 72adbe1f0d
commit 6d63211d35
No known key found for this signature in database
GPG key ID: 1D2A29322FBB6FCB
10 changed files with 454 additions and 859 deletions

View file

@ -0,0 +1,118 @@
package oauth
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/davidallendj/go-utils/httpx"
)
func (client *Client) IsFlowInitiated() bool {
return client.FlowId != ""
}
func (client *Client) BuildAuthorizationUrl(issuer string, state string) string {
return issuer + "?" + "client_id=" + client.Id +
"&redirect_uri=" + url.QueryEscape(strings.Join(client.RedirectUris, ",")) +
"&response_type=code" + // this has to be set to "code"
"&state=" + state +
"&scope=" + strings.Join(client.Scope, "+") +
"&resource=" + url.QueryEscape("http://127.0.0.1:4444/oauth2/token")
}
func (client *Client) InitiateLoginFlow(loginUrl string) error {
// kratos: GET /self-service/login/api
req, err := http.NewRequest("GET", loginUrl, bytes.NewBuffer([]byte{}))
if err != nil {
return fmt.Errorf("failed to make request: %v", err)
}
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to do request: %v", err)
}
defer res.Body.Close()
// get the flow ID from response
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err)
}
var flowData map[string]any
err = json.Unmarshal(body, &flowData)
if err != nil {
return fmt.Errorf("failed to unmarshal flow data: %v\n%v", err, string(body))
} else {
client.FlowId = flowData["id"].(string)
}
return nil
}
func (client *Client) FetchFlowData(url string) (map[string]any, error) {
//kratos: GET /self-service/login/flows?id={flowId}
// replace {id} in string with actual value
url = strings.ReplaceAll(url, "{id}", client.FlowId)
_, b, err := httpx.MakeHttpRequest(url, http.MethodGet, nil, nil)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
var flowData map[string]any
err = json.Unmarshal(b, &flowData)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal flow data: %v", err)
}
return flowData, nil
}
func (client *Client) FetchCSRFToken(flowUrl string) error {
data, err := client.FetchFlowData(flowUrl)
if err != nil {
return fmt.Errorf("failed to fetch flow data: %v", err)
}
// iterate through nodes and extract the CSRF token attribute from the flow data
ui := data["ui"].(map[string]any)
nodes := ui["nodes"].([]any)
for _, node := range nodes {
attrs := node.(map[string]any)["attributes"].(map[string]any)
name := attrs["name"].(string)
if name == "csrf_token" {
client.CsrfToken = attrs["value"].(string)
return nil
}
}
return fmt.Errorf("failed to extract CSRF token: not found")
}
func (client *Client) FetchTokenFromAuthenticationServer(code string, remoteUrl string, state string) ([]byte, error) {
body := url.Values{
"grant_type": {"authorization_code"},
"client_id": {client.Id},
"client_secret": {client.Secret},
"redirect_uri": {strings.Join(client.RedirectUris, ",")},
}
// add optional params if valid
if code != "" {
body["code"] = []string{code}
}
if state != "" {
body["state"] = []string{state}
}
res, err := http.PostForm(remoteUrl, body)
if err != nil {
return nil, fmt.Errorf("failed to get ID token: %s", err)
}
defer res.Body.Close()
// domain, _ := url.Parse("http://127.0.0.1")
// client.Jar.SetCookies(domain, res.Cookies())
return io.ReadAll(res.Body)
}

227
internal/oauth/client.go Normal file
View file

@ -0,0 +1,227 @@
package oauth
import (
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"slices"
"strings"
"github.com/davidallendj/go-utils/httpx"
"github.com/davidallendj/go-utils/util"
"golang.org/x/net/publicsuffix"
)
type Client struct {
http.Client
Id string `db:"id" yaml:"id"`
Secret string `db:"secret" yaml:"secret"`
Name string `db:"name" yaml:"name"`
Description string `db:"description" yaml:"description"`
Issuer string `db:"issuer" yaml:"issuer"`
RegistrationAccessToken string `db:"registration_access_token" yaml:"registration-access-token"`
RedirectUris []string `db:"redirect_uris" yaml:"redirect-uris"`
Scope []string `db:"scope" yaml:"scope"`
Audience []string `db:"audience" yaml:"audience"`
FlowId string
CsrfToken string
}
func NewClient() *Client {
return &Client{}
}
func (client *Client) ClearCookies() {
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
client.Jar = jar
}
func (client *Client) IsOAuthClientRegistered(clientUrl string) (bool, error) {
_, _, err := httpx.MakeHttpRequest(clientUrl, http.MethodGet, nil, nil)
if err != nil {
return false, fmt.Errorf("failed to make request: %v", err)
}
// TODO: need to check contents of actual response
return true, nil
}
func (client *Client) GetOAuthClient(clientUrl string) error {
_, b, err := httpx.MakeHttpRequest(clientUrl, http.MethodGet, nil, nil)
if err != nil {
return fmt.Errorf("failed to make request: %v", err)
}
fmt.Printf("GetOAuthClient: %v\n", string(b))
var data []map[string]any
err = json.Unmarshal(b, &data)
if err != nil {
return fmt.Errorf("failed to unmarshal JSON: %v", err)
}
index := slices.IndexFunc(data, func(c map[string]any) bool {
if c["client_id"] == nil {
return false
}
return c["client_id"].(string) == client.Id
})
if index < 0 {
return fmt.Errorf("client not found")
}
// cast the redirect_uris from []any to []string and extract registration token
foundClient := data[index]
for _, uri := range foundClient["redirect_uris"].([]any) {
client.RedirectUris = append(client.RedirectUris, uri.(string))
}
if foundClient["registration-access-token"] != nil {
client.RegistrationAccessToken = foundClient["registration-access-token"].(string)
}
return nil
}
func (client *Client) CreateOAuthClient(registerUrl string) ([]byte, error) {
// hydra endpoint: POST /clients
audience := util.QuoteArrayStrings(client.Audience)
body := httpx.Body(fmt.Sprintf(`{
"client_id": "%s",
"client_name": "%s",
"client_secret": "%s",
"token_endpoint_auth_method": "client_secret_post",
"scope": "%s",
"grant_types": ["urn:ietf:params:oauth:grant-type:jwt-bearer"],
"response_types": ["token"],
"redirect_uris": ["http://127.0.0.1:3333/callback"],
"state": 12345678910,
"audience": [%s]
}`, client.Id, client.Id, client.Secret, strings.Join(client.Scope, " "), strings.Join(audience, ","),
))
headers := httpx.Headers{
"Content-Type": "application/json",
}
_, b, err := httpx.MakeHttpRequest(registerUrl, http.MethodPost, []byte(body), headers)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
var rjson map[string]any
err = json.Unmarshal(b, &rjson)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal response body: %v", err)
}
// check for error first
errJson := rjson["error"]
if errJson == nil {
// set the client ID and secret of registered client
client.Id = rjson["client_id"].(string)
client.Secret = rjson["client_secret"].(string)
client.RegistrationAccessToken = rjson["registration_access_token"].(string)
} else {
return b, nil
}
return b, err
}
func (client *Client) RegisterOAuthClient(registerUrl string) ([]byte, error) {
// hydra endpoint: POST /oauth2/register
if registerUrl == "" {
return nil, fmt.Errorf("no URL provided")
}
audience := util.QuoteArrayStrings(client.Audience)
body := httpx.Body(fmt.Sprintf(`{
"client_name": "opaal",
"token_endpoint_auth_method": "client_secret_post",
"scope": "%s",
"grant_types": ["urn:ietf:params:oauth:grant-type:jwt-bearer"],
"response_types": ["token"],
"redirect_uris": ["http://127.0.0.1:3333/callback"],
"state": 12345678910,
"audience": [%s]
}`, strings.Join(client.Scope, " "), strings.Join(audience, ","),
))
headers := httpx.Headers{
"Content-Type": "application/json",
}
_, b, err := httpx.MakeHttpRequest(registerUrl, http.MethodPost, body, headers)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
var rjson map[string]any
err = json.Unmarshal(b, &rjson)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal response body: %v", err)
}
// check for error first
errJson := rjson["error"]
if errJson == nil {
// set the client ID and secret of registered client
client.Id = rjson["client_id"].(string)
client.Secret = rjson["client_secret"].(string)
client.RegistrationAccessToken = rjson["registration_access_token"].(string)
} else {
return b, nil
}
return b, err
}
func (client *Client) AuthorizeOAuthClient(authorizeUrl string) ([]byte, error) {
// set the authorization header
body := []byte("grant_type=" + url.QueryEscape("urn:ietf:params:oauth:grant-type:jwt-bearer") +
"&scope=" + strings.Join(client.Scope, "+") +
"&client_id=" + client.Id +
"&client_secret=" + client.Secret +
"&redirect_uri=" + url.QueryEscape("http://127.0.0.1:3333/callback") + // FIXME: needs to not be hardcorded
"&response_type=token" +
"&state=12345678910",
)
headers := httpx.Headers{
"Authorization": "Bearer " + client.RegistrationAccessToken,
"Content-Type": "application/x-www-form-urlencoded",
}
_, b, err := httpx.MakeHttpRequest(authorizeUrl, http.MethodPost, body, headers)
if err != nil {
return nil, fmt.Errorf("failed to make HTTP request: %v", err)
}
return b, nil
}
func (client *Client) PerformTokenGrant(clientUrl string, encodedJwt string) ([]byte, error) {
// hydra endpoint: /oauth/token
body := "grant_type=" + url.QueryEscape("urn:ietf:params:oauth:grant-type:jwt-bearer") +
"&client_id=" + client.Id +
"&client_secret=" + client.Secret +
"&redirect_uri=" + url.QueryEscape("http://127.0.0.1:3333/callback")
// add optional params if valid
if encodedJwt != "" {
body += "&assertion=" + encodedJwt
}
if client.Scope != nil || len(client.Scope) > 0 {
body += "&scope=" + strings.Join(client.Scope, "+")
}
headers := httpx.Headers{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + client.RegistrationAccessToken,
}
_, b, err := httpx.MakeHttpRequest(clientUrl, http.MethodPost, []byte(body), headers)
// set flow ID back to empty string to indicate a completed flow
client.FlowId = ""
return b, err
}
func (client *Client) DeleteOAuthClient(clientUrl string) error {
_, _, err := httpx.MakeHttpRequest(clientUrl+"/"+client.Id, http.MethodDelete, nil, nil)
if err != nil {
return fmt.Errorf("failed to make request: %v", err)
}
return nil
}

View file

@ -0,0 +1,32 @@
package oauth
import (
"fmt"
"net/http"
"github.com/davidallendj/go-utils/httpx"
)
func (client *Client) CreateIdentity(url string, idToken string) error {
// kratos endpoint: /admin/identities
body := []byte(`{
"schema_id": "preset://email",
"traits": {
"email": "docs@example.org"
}
}`)
headers := httpx.Headers{
"Content-Type": "application/json",
"Authorization": fmt.Sprintf("Bearer %s", idToken),
}
_, _, err := httpx.MakeHttpRequest(url, http.MethodPost, body, headers)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err)
}
return nil
}
func (client *Client) FetchIdentities(remoteUrl string) ([]byte, error) {
_, b, err := httpx.MakeHttpRequest(remoteUrl, http.MethodGet, []byte{}, httpx.Headers{})
return b, err
}

99
internal/oauth/trusted.go Normal file
View file

@ -0,0 +1,99 @@
package oauth
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/davidallendj/go-utils/httpx"
"github.com/lestrrat-go/jwx/v2/jwk"
)
type TrustedIssuer struct {
Id string `db:"id" yaml:"id"`
AllowAnySubject bool `db:"allow_any_subject" yaml:"allow-any-subject"`
ExpiresAt time.Time `db:"expires_at" yaml:"expires-at"`
Issuer string `db:"issuer" yaml:"issuer"`
PublicKey jwk.Key `db:"public_key" yaml:"public-key"`
Scope []string `db:"scope" yaml:"scope"`
Subject string `db:"subject" yaml:"subject"`
}
func NewTrustedIssuer() *TrustedIssuer {
return &TrustedIssuer{
AllowAnySubject: false,
ExpiresAt: time.Now().Add(time.Hour),
Scope: []string{"openid"},
Subject: "1",
}
}
func (ti *TrustedIssuer) IsTrustedIssuerValid() bool {
err := ti.PublicKey.Validate()
return ti.Issuer != "" && err == nil && ti.Subject != ""
}
func ParseString(b []byte) (*TrustedIssuer, error) {
// take data from JSON to populate fields
ti := &TrustedIssuer{}
data := map[string]any{}
json.Unmarshal(b, &data)
return ti, nil
}
func (client *Client) ListTrustedIssuers(url string) ([]TrustedIssuer, error) {
// hydra endpoint: GET /admin/trust/grants/jwt-bearer/issuers
_, b, err := httpx.MakeHttpRequest(url, http.MethodGet, nil, nil)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
// unmarshal results into TrustedIssuers objects
trustedIssuers := []TrustedIssuer{}
err = json.Unmarshal(b, &trustedIssuers)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON: %v", err)
}
return trustedIssuers, nil
}
func (client *Client) AddTrustedIssuer(url string, ti *TrustedIssuer) ([]byte, error) {
// hydra endpoint: POST /admin/trust/grants/jwt-bearer/issuers
quotedScopes := make([]string, len(client.Scope))
for i, s := range client.Scope {
quotedScopes[i] = fmt.Sprintf("\"%s\"", s)
}
// NOTE: Can also include "jwks_uri" instead of "jwk"
body := map[string]any{
"allow_any_subject": ti.AllowAnySubject,
"issuer": ti.Issuer,
"expires_at": ti.ExpiresAt,
"jwk": ti.PublicKey,
"scope": client.Scope,
}
if !ti.AllowAnySubject {
body["subject"] = ti.Subject
}
b, err := json.Marshal(body)
fmt.Printf("request: %v\n", string(b))
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %v", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to do request: %v", err)
}
defer res.Body.Close()
return io.ReadAll(res.Body)
}