Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip: Multiple principals for a Subject #1317

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions internal/accesscontext/access_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ package accesscontext

import (
"context"

"github.com/dadrus/heimdall/internal/subject"
)

type ctxKey struct{}

type accessContext struct {
err error
subject string
subject subject.Subject
}

func New(ctx context.Context) context.Context {
Expand All @@ -45,16 +47,16 @@ func SetError(ctx context.Context, err error) {
}
}

func Subject(ctx context.Context) string {
func Subject(ctx context.Context) subject.Subject {
if c, ok := ctx.Value(ctxKey{}).(*accessContext); ok {
return c.subject
}

return ""
return subject.Subject{}
}

func SetSubject(ctx context.Context, subject string) {
func SetSubject(ctx context.Context, sub subject.Subject) {
if c, ok := ctx.Value(ctxKey{}).(*accessContext); ok {
c.subject = subject
c.subject = sub
}
}
13 changes: 10 additions & 3 deletions internal/handler/middleware/grpc/accesslog/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,22 +110,29 @@ func (i *accessLogInterceptor) finalizeTransaction(
func logAccessStatus(ctx context.Context, event *zerolog.Event, err error) *zerolog.Event {
subject := accesscontext.Subject(ctx)
accessErr := accesscontext.Error(ctx)
dict := zerolog.Dict()

if len(subject) != 0 {
for _, v := range subject {
dict = dict.Str("id", v.ID)
}
}

switch {
case err != nil:
if len(subject) != 0 {
event.Str("_subject", subject)
event.Dict("_subject", dict)
}

event.Err(err).Bool("_access_granted", false)
case accessErr != nil:
if len(subject) != 0 {
event.Str("_subject", subject)
event.Dict("_subject", dict)
}

event.Err(accessErr).Bool("_access_granted", false)
default:
event.Str("_subject", subject).Bool("_access_granted", true)
event.Dict("_subject", dict).Bool("_access_granted", true)
}

return event
Expand Down
15 changes: 8 additions & 7 deletions internal/handler/middleware/grpc/accesslog/interceptor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (

"github.com/dadrus/heimdall/internal/accesscontext"
mocks2 "github.com/dadrus/heimdall/internal/handler/middleware/grpc/mocks"
"github.com/dadrus/heimdall/internal/subject"
"github.com/dadrus/heimdall/internal/x/testsupport"
)

Expand Down Expand Up @@ -76,7 +77,7 @@ func TestAccessLogInterceptorForKnownService(t *testing.T) {
m.On("Check",
mock.MatchedBy(
func(ctx context.Context) bool {
accesscontext.SetSubject(ctx, "foo")
accesscontext.SetSubject(ctx, subject.Subject{"Subject": &subject.Principal{ID: "foo"}})

return true
},
Expand Down Expand Up @@ -112,7 +113,7 @@ func TestAccessLogInterceptorForKnownService(t *testing.T) {
assert.Equal(t, logEvent1["_trace_id"], logEvent2["_trace_id"])
assert.Equal(t, logEvent1["_parent_id"], logEvent2["_parent_id"])
assert.Equal(t, true, logEvent2["_access_granted"]) //nolint:testifylint
assert.Equal(t, "foo", logEvent2["_subject"])
assert.Equal(t, map[string]any{"id": "foo"}, logEvent2["_subject"])
assert.InDelta(t, float64(codes.OK), logEvent2["_grpc_status_code"], 0.001)
assert.Equal(t, "TX finished", logEvent2["message"])
},
Expand Down Expand Up @@ -184,7 +185,7 @@ func TestAccessLogInterceptorForKnownService(t *testing.T) {
m.On("Check",
mock.MatchedBy(
func(ctx context.Context) bool {
accesscontext.SetSubject(ctx, "bar")
accesscontext.SetSubject(ctx, subject.Subject{"Subject": &subject.Principal{ID: "bar"}})
accesscontext.SetError(ctx, errors.New("test error"))

return true
Expand Down Expand Up @@ -221,7 +222,7 @@ func TestAccessLogInterceptorForKnownService(t *testing.T) {
assert.Equal(t, logEvent1["_trace_id"], logEvent2["_trace_id"])
assert.Equal(t, logEvent1["_parent_id"], logEvent2["_parent_id"])
assert.Equal(t, false, logEvent2["_access_granted"]) //nolint:testifylint
assert.Equal(t, "bar", logEvent2["_subject"])
assert.Equal(t, map[string]any{"id": "bar"}, logEvent2["_subject"])
assert.Equal(t, "test error", logEvent2["error"])
assert.InDelta(t, float64(codes.OK), logEvent2["_grpc_status_code"], 0.001)
assert.Equal(t, "TX finished", logEvent2["message"])
Expand Down Expand Up @@ -275,11 +276,11 @@ func TestAccessLogInterceptorForKnownService(t *testing.T) {
// THEN
srv.Stop()

events := strings.Split(tb.CollectedLog(), "}")
require.Len(t, events, 3)
events := strings.Split(tb.CollectedLog(), "}{")
require.Len(t, events, 2)

require.NoError(t, json.Unmarshal([]byte(events[0]+"}"), &logLine1))
require.NoError(t, json.Unmarshal([]byte(events[1]+"}"), &logLine2))
require.NoError(t, json.Unmarshal([]byte("{"+events[1]), &logLine2))

tc.assert(t, logLine1, logLine2)
handler.AssertExpectations(t)
Expand Down
7 changes: 6 additions & 1 deletion internal/handler/middleware/http/accesslog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,12 @@ func logAccessStatus(ctx context.Context, event *zerolog.Event, statusCode int)
err := accesscontext.Error(ctx)

if len(subject) != 0 {
event.Str("_subject", subject)
dict := zerolog.Dict()
for _, v := range subject {
dict = dict.Str("id", v.ID)
}

event.Dict("_subject", dict)
}

if err != nil || statusCode >= 300 {
Expand Down
19 changes: 10 additions & 9 deletions internal/handler/middleware/http/accesslog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"go.opentelemetry.io/otel/trace"

"github.com/dadrus/heimdall/internal/accesscontext"
"github.com/dadrus/heimdall/internal/subject"
"github.com/dadrus/heimdall/internal/x/testsupport"
)

Expand All @@ -63,7 +64,7 @@ func TestHandlerExecution(t *testing.T) {
handleRequest: func(t *testing.T, rw http.ResponseWriter, req *http.Request) {
t.Helper()

accesscontext.SetSubject(req.Context(), "foo")
accesscontext.SetSubject(req.Context(), subject.Subject{"Subject": &subject.Principal{ID: "foo"}})
rw.WriteHeader(http.StatusOK)
},
assert: func(t *testing.T, clientReq *http.Request, logEvent1, logEvent2 map[string]any) {
Expand Down Expand Up @@ -100,7 +101,7 @@ func TestHandlerExecution(t *testing.T) {
assert.Contains(t, logEvent2, "_body_bytes_sent")
assert.InDelta(t, float64(http.StatusOK), logEvent2["_http_status_code"], 0.001)
assert.Equal(t, true, logEvent2["_access_granted"]) //nolint:testifylint
assert.Equal(t, "foo", logEvent2["_subject"])
assert.Equal(t, map[string]any{"id": "foo"}, logEvent2["_subject"])
assert.Contains(t, logEvent2, "_http_user_agent")
assert.Equal(t, "TX finished", logEvent2["message"])
},
Expand Down Expand Up @@ -182,7 +183,7 @@ func TestHandlerExecution(t *testing.T) {
handleRequest: func(t *testing.T, rw http.ResponseWriter, req *http.Request) {
t.Helper()

accesscontext.SetSubject(req.Context(), "bar")
accesscontext.SetSubject(req.Context(), subject.Subject{"Subject": &subject.Principal{ID: "foo"}})
accesscontext.SetError(req.Context(), errors.New("test error"))
rw.WriteHeader(http.StatusUnauthorized)
},
Expand Down Expand Up @@ -220,7 +221,7 @@ func TestHandlerExecution(t *testing.T) {
assert.Contains(t, logEvent2, "_body_bytes_sent")
assert.InDelta(t, float64(http.StatusUnauthorized), logEvent2["_http_status_code"], 0.001)
assert.Equal(t, false, logEvent2["_access_granted"]) //nolint:testifylint
assert.Equal(t, "bar", logEvent2["_subject"])
assert.Equal(t, map[string]any{"id": "foo"}, logEvent2["_subject"])
assert.Equal(t, "test error", logEvent2["error"])
assert.Contains(t, logEvent2, "_http_user_agent")
assert.Equal(t, "TX finished", logEvent2["message"])
Expand All @@ -233,7 +234,7 @@ func TestHandlerExecution(t *testing.T) {
handleRequest: func(t *testing.T, rw http.ResponseWriter, req *http.Request) {
t.Helper()

accesscontext.SetSubject(req.Context(), "bar")
accesscontext.SetSubject(req.Context(), subject.Subject{"Subject": &subject.Principal{ID: "bar"}})
rw.WriteHeader(http.StatusSeeOther)
},
assert: func(t *testing.T, clientReq *http.Request, logEvent1, logEvent2 map[string]any) {
Expand Down Expand Up @@ -270,7 +271,7 @@ func TestHandlerExecution(t *testing.T) {
assert.Contains(t, logEvent2, "_body_bytes_sent")
assert.InDelta(t, float64(http.StatusSeeOther), logEvent2["_http_status_code"], 0.001)
assert.Equal(t, false, logEvent2["_access_granted"]) //nolint:testifylint
assert.Equal(t, "bar", logEvent2["_subject"])
assert.Equal(t, map[string]any{"id": "bar"}, logEvent2["_subject"])
assert.Contains(t, logEvent2, "_http_user_agent")
assert.Equal(t, "TX finished", logEvent2["message"])
},
Expand Down Expand Up @@ -320,16 +321,16 @@ func TestHandlerExecution(t *testing.T) {
require.NoError(t, err)
require.NoError(t, resp.Body.Close())

events := strings.Split(tb.CollectedLog(), "}")
require.Len(t, events, 3)
events := strings.Split(tb.CollectedLog(), "}{")
require.Len(t, events, 2)

var (
logLine1 map[string]any
logLine2 map[string]any
)

require.NoError(t, json.Unmarshal([]byte(events[0]+"}"), &logLine1))
require.NoError(t, json.Unmarshal([]byte(events[1]+"}"), &logLine2))
require.NoError(t, json.Unmarshal([]byte("{"+events[1]), &logLine2))

tc.assert(t, req, logLine1, logLine2)
})
Expand Down
23 changes: 17 additions & 6 deletions internal/heimdall/mocks/context.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 17 additions & 6 deletions internal/heimdall/mocks/jwt_signer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading