Skip to content

Commit

Permalink
feat(op): allow returning of parent errors to client
Browse files Browse the repository at this point in the history
  • Loading branch information
muhlemmer committed Aug 1, 2024
1 parent b9bcd6a commit 2cbf96e
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
24 changes: 24 additions & 0 deletions pkg/oidc/error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package oidc

import (
"encoding/json"
"errors"
"fmt"
"log/slog"
Expand Down Expand Up @@ -133,6 +134,24 @@ type Error struct {
Description string `json:"error_description,omitempty" schema:"error_description,omitempty"`
State string `json:"state,omitempty" schema:"state,omitempty"`
redirectDisabled bool `schema:"-"`
returnParent bool `schema:"-"`
}

func (e *Error) MarshalJSON() ([]byte, error) {
m := struct {
Error errorType `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
State string `json:"state,omitempty"`
Parent string `json:"parent,omitempty"`
}{
Error: e.ErrorType,
ErrorDescription: e.Description,
State: e.State,
}
if e.returnParent {
m.Parent = e.Parent.Error()
}
return json.Marshal(m)
}

func (e *Error) Error() string {
Expand Down Expand Up @@ -165,6 +184,11 @@ func (e *Error) WithParent(err error) *Error {
return e
}

func (e *Error) WithReturnParentToClient(b bool) *Error {
e.returnParent = b
return e
}

func (e *Error) WithDescription(desc string, args ...any) *Error {
e.Description = fmt.Sprintf(desc, args...)
return e
Expand Down
39 changes: 39 additions & 0 deletions pkg/oidc/error_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package oidc

import (
"encoding/json"
"errors"
"io"
"log/slog"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestDefaultToServerError(t *testing.T) {
Expand Down Expand Up @@ -151,3 +154,39 @@ func TestError_LogValue(t *testing.T) {
})
}
}

func TestError_MarshalJSON(t *testing.T) {
tests := []struct {
name string
e *Error
want string
}{
{
name: "simple error",
e: ErrAccessDenied(),
want: `{"error":"access_denied","error_description":"The authorization request was denied."}`,
},
{
name: "with description",
e: ErrAccessDenied().WithDescription("oops"),
want: `{"error":"access_denied","error_description":"oops"}`,
},
{
name: "with parent",
e: ErrServerError().WithParent(errors.New("oops")),
want: `{"error":"server_error"}`,
},
{
name: "with return parent",
e: ErrServerError().WithParent(errors.New("oops")).WithReturnParentToClient(true),
want: `{"error":"server_error","parent":"oops"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := json.Marshal(tt.e)
require.NoError(t, err)
assert.JSONEq(t, tt.want, string(got))
})
}
}

0 comments on commit 2cbf96e

Please sign in to comment.