diff --git a/internal/client/repository/http/http_client.go b/internal/client/repository/http/http_client.go index 58c5d09..fae0762 100644 --- a/internal/client/repository/http/http_client.go +++ b/internal/client/repository/http/http_client.go @@ -8,27 +8,40 @@ import ( "net/http" "net/url" + "github.com/tomnomnom/linkheader" "golang.org/x/exp/slices" + "willnorris.com/go/microformats" "source.toby3d.me/toby3d/auth/internal/client" "source.toby3d.me/toby3d/auth/internal/common" "source.toby3d.me/toby3d/auth/internal/domain" - "source.toby3d.me/toby3d/auth/internal/httputil" ) -type httpClientRepository struct { - client *http.Client -} +type ( + //nolint:tagliatelle,lll + Response struct { + TicketEndpoint domain.URL `json:"ticket_endpoint"` + AuthorizationEndpoint domain.URL `json:"authorization_endpoint"` + IntrospectionEndpoint domain.URL `json:"introspection_endpoint"` + RevocationEndpoint domain.URL `json:"revocation_endpoint,omitempty"` + ServiceDocumentation domain.URL `json:"service_documentation,omitempty"` + TokenEndpoint domain.URL `json:"token_endpoint"` + UserinfoEndpoint domain.URL `json:"userinfo_endpoint,omitempty"` + Microsub domain.URL `json:"microsub"` + Issuer domain.URL `json:"issuer"` + Micropub domain.URL `json:"micropub"` + GrantTypesSupported []domain.GrantType `json:"grant_types_supported,omitempty"` + IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported,omitempty"` + RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported,omitempty"` + ScopesSupported []domain.Scope `json:"scopes_supported,omitempty"` + ResponseTypesSupported []domain.ResponseType `json:"response_types_supported,omitempty"` + CodeChallengeMethodsSupported []domain.CodeChallengeMethod `json:"code_challenge_methods_supported"` + AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"` + } -const ( - DefaultMaxRedirectsCount int = 10 - - hApp string = "h-app" - hXApp string = "h-x-app" - propertyLogo string = "logo" - propertyName string = "name" - propertyURL string = "url" - relRedirectURI string = "redirect_uri" + httpClientRepository struct { + client *http.Client + } ) func NewHTTPClientRepository(c *http.Client) client.Repository { @@ -46,9 +59,9 @@ func (repo httpClientRepository) Get(ctx context.Context, cid domain.ClientID) ( out := &domain.Client{ ID: cid, RedirectURI: make([]*url.URL, 0), - Logo: make([]*url.URL, 0), - URL: make([]*url.URL, 0), - Name: make([]string, 0), + Logo: nil, + URL: nil, + Name: "", } if cid.IsLocalhost() { @@ -64,71 +77,82 @@ func (repo httpClientRepository) Get(ctx context.Context, cid domain.ClientID) ( return nil, fmt.Errorf("%w: status on client page is not 200", client.ErrNotExist) } - extract(resp.Body, resp.Request.URL, out, resp.Header.Get(common.HeaderLink)) + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("cannot read response body: %w", err) + } + + // NOTE(toby3d): fetch redirect uri's and application profile from HTML nodes + mf2 := microformats.Parse(bytes.NewReader(body), resp.Request.URL) + + for i := range mf2.Items { + if !slices.Contains(mf2.Items[i].Type, common.HApp) && + !slices.Contains(mf2.Items[i].Type, common.HXApp) { + continue + } + + parseProfile(mf2.Items[i].Properties, out) + } + + for _, val := range mf2.Rels[common.RelRedirectURI] { + var u *url.URL + if u, err = url.Parse(val); err == nil { + out.RedirectURI = append(out.RedirectURI, u) + } + } + + // NOTE(toby3d): fetch redirect uri's from Link header + for _, link := range linkheader.Parse(resp.Header.Get(common.HeaderLink)) { + if link.Rel != common.RelRedirectURI { + continue + } + + var u *url.URL + if u, err = url.Parse(link.URL); err == nil { + out.RedirectURI = append(out.RedirectURI, u) + } + } return out, nil } -//nolint:gocognit,cyclop -func extract(r io.Reader, u *url.URL, dst *domain.Client, header string) { - body, _ := io.ReadAll(r) - - for _, endpoint := range httputil.ExtractEndpoints(bytes.NewReader(body), u, header, relRedirectURI) { - if !containsUrl(dst.RedirectURI, endpoint) { - dst.RedirectURI = append(dst.RedirectURI, endpoint) - } - } - - for _, itemType := range []string{hApp, hXApp} { - for _, name := range httputil.ExtractProperty(bytes.NewReader(body), u, itemType, propertyName) { - if n, ok := name.(string); ok && !slices.Contains(dst.Name, n) { - dst.Name = append(dst.Name, n) - } - } - - for _, logo := range httputil.ExtractProperty(bytes.NewReader(body), u, itemType, propertyLogo) { - var ( - logoURL *url.URL - err error - ) - - switch l := logo.(type) { - case string: - logoURL, err = url.Parse(l) - case map[string]string: - if value, ok := l["value"]; ok { - logoURL, err = url.Parse(value) - } - } - - if err != nil || containsUrl(dst.Logo, logoURL) { - continue - } - - dst.Logo = append(dst.Logo, logoURL) - } - - for _, property := range httputil.ExtractProperty(bytes.NewReader(body), u, itemType, propertyURL) { - prop, ok := property.(string) - if !ok { - continue - } - - if u, err := url.Parse(prop); err == nil && !containsUrl(dst.URL, u) { - dst.URL = append(dst.URL, u) - } - } - } -} - -func containsUrl(src []*url.URL, find *url.URL) bool { - for i := range src { - if src[i].String() != find.String() { +func parseProfile(src map[string][]any, dst *domain.Client) { + for _, val := range src[common.PropertyName] { + v, ok := val.(string) + if !ok { continue } - return true + dst.Name = v + + break } - return false + for _, val := range src[common.PropertyURL] { + v, ok := val.(string) + if !ok { + continue + } + + var err error + if dst.URL, err = url.Parse(v); err != nil { + continue + } + + break + } + + for _, val := range src[common.PropertyLogo] { + v, ok := val.(string) + if !ok { + continue + } + + var err error + if dst.Logo, err = url.Parse(v); err != nil { + continue + } + + break + } } diff --git a/internal/client/repository/http/http_client_test.go b/internal/client/repository/http/http_client_test.go index d1fb87a..6c36df4 100644 --- a/internal/client/repository/http/http_client_test.go +++ b/internal/client/repository/http/http_client_test.go @@ -75,7 +75,7 @@ func testHandler(tb testing.TB, client domain.Client) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set(common.HeaderContentType, common.MIMETextHTMLCharsetUTF8) - w.Header().Set(common.HeaderLink, `<`+client.RedirectURI[0].String()+`>; rel="redirect_uri"`) - fmt.Fprintf(w, testBody, client.Name[0], client.URL[0], client.Logo[0], client.RedirectURI[1]) + w.Header().Set(common.HeaderLink, `<`+client.RedirectURI[1].String()+`>; rel="redirect_uri"`) + fmt.Fprintf(w, testBody, client.Name, client.URL, client.Logo, client.RedirectURI[0]) }) } diff --git a/internal/common/common.go b/internal/common/common.go index 9a5a60f..09db682 100644 --- a/internal/common/common.go +++ b/internal/common/common.go @@ -27,4 +27,29 @@ const ( HeaderXCSRFToken string = "X-CSRF-Token" ) +const ( + HApp string = "h-app" + HCard string = "h-card" + HXApp string = "h-x-app" +) + +const ( + PropertyEmail string = "email" + PropertyLogo string = "logo" + PropertyName string = "name" + PropertyPhoto string = "photo" + PropertyURL string = "url" +) + +const ( + RelAuthn string = "authn" + RelAuthorizationEndpoint string = "authorization_endpoint" + RelIndieAuthMetadata string = "indieauth-metadata" + RelMicropub string = "micropub" + RelMicrosub string = "microsub" + RelRedirectURI string = "redirect_uri" + RelTicketEndpoint string = "ticket_endpoint" + RelTokenEndpoint string = "token_endpoint" +) + const Und string = "und" diff --git a/internal/domain/client.go b/internal/domain/client.go index 44131a3..9bf8821 100644 --- a/internal/domain/client.go +++ b/internal/domain/client.go @@ -9,21 +9,21 @@ import ( // Client describes the client requesting data about the user. type Client struct { + Logo *url.URL + URL *url.URL ID ClientID - Logo []*url.URL + Name string RedirectURI []*url.URL - URL []*url.URL - Name []string } // NewClient creates a new empty Client with provided ClientID, if any. func NewClient(cid ClientID) *Client { return &Client{ ID: cid, - Logo: make([]*url.URL, 0), + Logo: nil, RedirectURI: make([]*url.URL, 0), - URL: make([]*url.URL, 0), - Name: make([]string, 0), + URL: nil, + Name: "", } } @@ -33,9 +33,9 @@ func TestClient(tb testing.TB) *Client { return &Client{ ID: *TestClientID(tb), - Name: []string{"Example App"}, - URL: []*url.URL{{Scheme: "https", Host: "app.example.com", Path: "/"}}, - Logo: []*url.URL{{Scheme: "https", Host: "app.example.com", Path: "/logo.png"}}, + Name: "Example App", + URL: &url.URL{Scheme: "https", Host: "app.example.com", Path: "/"}, + Logo: &url.URL{Scheme: "https", Host: "app.example.com", Path: "/logo.png"}, RedirectURI: []*url.URL{ {Scheme: "https", Host: "app.example.com", Path: "/redirect"}, {Scheme: "https", Host: "app.example.net", Path: "/redirect"}, @@ -81,30 +81,3 @@ func (c *Client) ValidateRedirectURI(redirectURI *url.URL) bool { return false } - -// GetName safe returns first name, if any. -func (c Client) GetName() string { - if len(c.Name) == 0 { - return "" - } - - return c.Name[0] -} - -// GetURL safe returns first URL, if any. -func (c Client) GetURL() *url.URL { - if len(c.URL) == 0 { - return nil - } - - return c.URL[0] -} - -// GetLogo safe returns first logo, if any. -func (c Client) GetLogo() *url.URL { - if len(c.Logo) == 0 { - return nil - } - - return c.Logo[0] -} diff --git a/internal/domain/client_test.go b/internal/domain/client_test.go index ae7cef8..0d376ac 100644 --- a/internal/domain/client_test.go +++ b/internal/domain/client_test.go @@ -13,8 +13,8 @@ func TestClient_ValidateRedirectURI(t *testing.T) { client := domain.TestClient(t) for name, in := range map[string]*url.URL{ - "client_id prefix": client.ID.URL().JoinPath("/callback"), - "registered redirect_uri": client.RedirectURI[len(client.RedirectURI)-1], + "prefix": client.ID.URL().JoinPath("/callback"), + "redirect_uri": client.RedirectURI[len(client.RedirectURI)-1], } { name, in := name, in @@ -27,30 +27,3 @@ func TestClient_ValidateRedirectURI(t *testing.T) { }) } } - -func TestClient_GetName(t *testing.T) { - t.Parallel() - - client := domain.TestClient(t) - if result := client.GetName(); result != client.Name[0] { - t.Errorf("GetName() = %v, want %v", result, client.Name[0]) - } -} - -func TestClient_GetURL(t *testing.T) { - t.Parallel() - - client := domain.TestClient(t) - if result := client.GetURL(); result != client.URL[0] { - t.Errorf("GetURL() = %v, want %v", result, client.URL[0]) - } -} - -func TestClient_GetLogo(t *testing.T) { - t.Parallel() - - client := domain.TestClient(t) - if result := client.GetLogo(); result != client.Logo[0] { - t.Errorf("GetLogo() = %v, want %v", result, client.Logo[0]) - } -} diff --git a/internal/domain/profile.go b/internal/domain/profile.go index 55fdb01..7c2272e 100644 --- a/internal/domain/profile.go +++ b/internal/domain/profile.go @@ -7,18 +7,18 @@ import ( // Profile describes the data about the user. type Profile struct { - Photo []*url.URL `json:"photo,omitempty"` - URL []*url.URL `json:"url,omitempty"` - Email []*Email `json:"email,omitempty"` - Name []string `json:"name,omitempty"` + Photo *url.URL `json:"photo,omitempty"` + URL *url.URL `json:"url,omitempty"` + Email *Email `json:"email,omitempty"` + Name string `json:"name,omitempty"` } func NewProfile() *Profile { return &Profile{ - Photo: make([]*url.URL, 0), - URL: make([]*url.URL, 0), - Email: make([]*Email, 0), - Name: make([]string, 0), + Photo: new(url.URL), + URL: new(url.URL), + Email: new(Email), + Name: "", } } @@ -27,61 +27,9 @@ func TestProfile(tb testing.TB) *Profile { tb.Helper() return &Profile{ - Email: []*Email{TestEmail(tb)}, - Name: []string{"Example User"}, - Photo: []*url.URL{{Scheme: "https", Host: "user.example.net", Path: "/photo.jpg"}}, - URL: []*url.URL{{Scheme: "https", Host: "user.example.net", Path: "/"}}, + Email: TestEmail(tb), + Name: "Example User", + Photo: &url.URL{Scheme: "https", Host: "user.example.net", Path: "/photo.jpg"}, + URL: &url.URL{Scheme: "https", Host: "user.example.net", Path: "/"}, } } - -func (p Profile) HasName() bool { - return len(p.Name) > 0 -} - -// GetName safe returns first name, if any. -func (p Profile) GetName() string { - if len(p.Name) == 0 { - return "" - } - - return p.Name[0] -} - -func (p Profile) HasURL() bool { - return len(p.URL) > 0 -} - -// GetURL safe returns first URL, if any. -func (p Profile) GetURL() *url.URL { - if len(p.URL) == 0 { - return nil - } - - return p.URL[0] -} - -func (p Profile) HasPhoto() bool { - return len(p.Photo) > 0 -} - -// GetPhoto safe returns first photo, if any. -func (p Profile) GetPhoto() *url.URL { - if len(p.Photo) == 0 { - return nil - } - - return p.Photo[0] -} - -func (p Profile) HasEmail() bool { - return len(p.Email) > 0 -} - -// GetEmail safe returns first email, if any. -func (p Profile) GetEmail() *Email { - if len(p.Email) == 0 { - return nil - } - - return p.Email[0] -} diff --git a/internal/httputil/httputil.go b/internal/httputil/httputil.go deleted file mode 100644 index 212c1f1..0000000 --- a/internal/httputil/httputil.go +++ /dev/null @@ -1,138 +0,0 @@ -package httputil - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/goccy/go-json" - "github.com/tomnomnom/linkheader" - "golang.org/x/exp/slices" - "willnorris.com/go/microformats" - - "source.toby3d.me/toby3d/auth/internal/common" - "source.toby3d.me/toby3d/auth/internal/domain" -) - -const RelIndieauthMetadata = "indieauth-metadata" - -var ErrEndpointNotExist = domain.NewError( - domain.ErrorCodeServerError, - "cannot found any endpoints", - "https://indieauth.net/source/#discovery-0", -) - -func ExtractFromMetadata(client *http.Client, u string) (*domain.Metadata, error) { - req, err := http.NewRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - resp, err := client.Do(req) - if err != nil { - return nil, err - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - buf := bytes.NewBuffer(body) - - endpoints := ExtractEndpoints(buf, resp.Request.URL, resp.Header.Get(common.HeaderLink), RelIndieauthMetadata) - if len(endpoints) == 0 { - return nil, ErrEndpointNotExist - } - - if resp, err = client.Get(endpoints[len(endpoints)-1].String()); err != nil { - return nil, fmt.Errorf("failed to fetch metadata endpoint configuration: %w", err) - } - - result := new(domain.Metadata) - if err = json.NewDecoder(resp.Body).Decode(result); err != nil { - return nil, fmt.Errorf("cannot unmarshal emtadata configuration: %w", err) - } - - return result, nil -} - -func ExtractEndpoints(body io.Reader, u *url.URL, linkHeader, rel string) []*url.URL { - results := make([]*url.URL, 0) - - urls, err := ExtractEndpointsFromHeader(linkHeader, rel) - if err == nil { - results = append(results, urls...) - } - - urls, err = ExtractEndpointsFromBody(body, u, rel) - if err == nil { - results = append(results, urls...) - } - - return results -} - -func ExtractEndpointsFromHeader(linkHeader, rel string) ([]*url.URL, error) { - results := make([]*url.URL, 0) - - for _, link := range linkheader.Parse(linkHeader) { - if !strings.EqualFold(link.Rel, rel) { - continue - } - - u, err := url.Parse(link.URL) - if err != nil { - return nil, fmt.Errorf("cannot parse header endpoint: %w", err) - } - - results = append(results, u) - } - - return results, nil -} - -func ExtractEndpointsFromBody(body io.Reader, u *url.URL, rel string) ([]*url.URL, error) { - endpoints, ok := microformats.Parse(body, u).Rels[rel] - if !ok || len(endpoints) == 0 { - return nil, ErrEndpointNotExist - } - - results := make([]*url.URL, 0) - - for i := range endpoints { - u, err := url.Parse(endpoints[i]) - if err != nil { - return nil, fmt.Errorf("cannot parse body endpoint: %w", err) - } - - results = append(results, u) - } - - return results, nil -} - -func ExtractProperty(body io.Reader, u *url.URL, itemType, key string) []any { - if data := microformats.Parse(body, u); data != nil { - return FindProperty(data.Items, itemType, key) - } - - return nil -} - -func FindProperty(src []*microformats.Microformat, itemType, key string) []any { - for _, item := range src { - if slices.Contains(item.Type, itemType) { - return item.Properties[key] - } - - if result := FindProperty(item.Children, itemType, key); result != nil { - return result - } - } - - return nil -} diff --git a/internal/httputil/httputil_test.go b/internal/httputil/httputil_test.go deleted file mode 100644 index 2bb8f74..0000000 --- a/internal/httputil/httputil_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package httputil_test - -import ( - "io" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/google/go-cmp/cmp" - - "source.toby3d.me/toby3d/auth/internal/httputil" -) - -const testBody = ` -
- - - - -