From 1257347df993ffe60a5dd2ea07dc8207c848a962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89mile=20R=C3=A9?= Date: Fri, 9 Jan 2026 11:23:42 +0100 Subject: [PATCH] Extract authn & authz utils MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Émile Ré --- ...onfigurationForm_createMutation.graphql.ts | 36 ++++++++++-- .../v1 => authn}/api_key_middleware.go | 17 +----- pkg/server/api/authn/context.go | 58 +++++++++++++++++++ .../identity_presence_middleware.go | 2 +- .../v1 => authn}/session_middleware.go | 23 +------- .../{connect/v1 => authz}/authorization.go | 7 ++- pkg/server/api/connect/v1/ctxkey.go | 19 ------ pkg/server/api/connect/v1/graphql_handler.go | 8 ++- pkg/server/api/connect/v1/resolver.go | 11 ++-- pkg/server/api/connect/v1/saml_handler.go | 3 +- pkg/server/api/connect/v1/scim_handler.go | 2 + pkg/server/api/connect/v1/v1_resolver.go | 48 +++++++-------- pkg/server/api/console/v1/graphql_handler.go | 4 +- pkg/server/api/console/v1/resolver.go | 17 +++--- pkg/server/api/console/v1/v1_resolver.go | 30 +++++----- pkg/server/api/mcp/v1/middleware.go | 6 +- pkg/server/api/mcp/v1/resolver.go | 4 +- pkg/server/api/mcp/v1/schema.resolvers.go | 6 +- pkg/server/api/mcp/v1/v1_handler.go | 4 +- pkg/server/api/trust/v1/resolver.go | 4 +- .../{api/connect/v1 => gqlutils}/httpctx.go | 6 +- 21 files changed, 185 insertions(+), 130 deletions(-) rename pkg/server/api/{connect/v1 => authn}/api_key_middleware.go (87%) create mode 100644 pkg/server/api/authn/context.go rename pkg/server/api/{connect/v1 => authn}/identity_presence_middleware.go (98%) rename pkg/server/api/{connect/v1 => authn}/session_middleware.go (85%) rename pkg/server/api/{connect/v1 => authz}/authorization.go (93%) delete mode 100644 pkg/server/api/connect/v1/ctxkey.go rename pkg/server/{api/connect/v1 => gqlutils}/httpctx.go (96%) diff --git a/apps/console/src/__generated__/iam/NewSAMLConfigurationForm_createMutation.graphql.ts b/apps/console/src/__generated__/iam/NewSAMLConfigurationForm_createMutation.graphql.ts index d09fcd0b5..2755ea2c5 100644 --- a/apps/console/src/__generated__/iam/NewSAMLConfigurationForm_createMutation.graphql.ts +++ b/apps/console/src/__generated__/iam/NewSAMLConfigurationForm_createMutation.graphql.ts @@ -1,5 +1,5 @@ /** - * @generated SignedSource<> + * @generated SignedSource<> * @lightSyntaxTransform * @nogrep */ @@ -33,6 +33,8 @@ export type NewSAMLConfigurationForm_createMutation$data = { readonly createSAMLConfiguration: { readonly samlConfigurationEdge: { readonly node: { + readonly canDelete: boolean; + readonly canUpdate: boolean; readonly domainVerificationToken: string | null | undefined; readonly domainVerifiedAt: string | null | undefined; readonly emailDomain: string; @@ -123,6 +125,32 @@ v3 = { "kind": "ScalarField", "name": "testLoginUrl", "storageKey": null + }, + { + "alias": "canUpdate", + "args": [ + { + "kind": "Literal", + "name": "action", + "value": "iam:saml-configuration:update" + } + ], + "kind": "ScalarField", + "name": "permission", + "storageKey": "permission(action:\"iam:saml-configuration:update\")" + }, + { + "alias": "canDelete", + "args": [ + { + "kind": "Literal", + "name": "action", + "value": "iam:saml-configuration:delete" + } + ], + "kind": "ScalarField", + "name": "permission", + "storageKey": "permission(action:\"iam:saml-configuration:delete\")" } ], "storageKey": null @@ -196,16 +224,16 @@ return { ] }, "params": { - "cacheID": "969d5fb34995f5cce359c792cbe1ff49", + "cacheID": "6ea275ac351f162aeeff7d75d7a3974d", "id": null, "metadata": {}, "name": "NewSAMLConfigurationForm_createMutation", "operationKind": "mutation", - "text": "mutation NewSAMLConfigurationForm_createMutation(\n $input: CreateSAMLConfigurationInput!\n) {\n createSAMLConfiguration(input: $input) {\n samlConfigurationEdge {\n node {\n id\n emailDomain\n enforcementPolicy\n domainVerificationToken\n domainVerifiedAt\n testLoginUrl\n }\n }\n }\n}\n" + "text": "mutation NewSAMLConfigurationForm_createMutation(\n $input: CreateSAMLConfigurationInput!\n) {\n createSAMLConfiguration(input: $input) {\n samlConfigurationEdge {\n node {\n id\n emailDomain\n enforcementPolicy\n domainVerificationToken\n domainVerifiedAt\n testLoginUrl\n canUpdate: permission(action: \"iam:saml-configuration:update\")\n canDelete: permission(action: \"iam:saml-configuration:delete\")\n }\n }\n }\n}\n" } }; })(); -(node as any).hash = "5a3b2e5d219b40ca096eece75d7b63b3"; +(node as any).hash = "af2894da24b742843908a60a7e4629f1"; export default node; diff --git a/pkg/server/api/connect/v1/api_key_middleware.go b/pkg/server/api/authn/api_key_middleware.go similarity index 87% rename from pkg/server/api/connect/v1/api_key_middleware.go rename to pkg/server/api/authn/api_key_middleware.go index c5eaff471..582fe3dec 100644 --- a/pkg/server/api/connect/v1/api_key_middleware.go +++ b/pkg/server/api/authn/api_key_middleware.go @@ -12,10 +12,9 @@ // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. -package connect_v1 +package authn import ( - "context" "errors" "fmt" "net/http" @@ -23,22 +22,12 @@ import ( "github.com/99designs/gqlgen/graphql" "github.com/vektah/gqlparser/v2/gqlerror" "go.gearno.de/kit/httpserver" - "go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/securetoken" "go.probo.inc/probo/pkg/server/gqlutils" ) -var ( - apiKeyContextKey = &ctxKey{name: "api_key"} -) - -func APIKeyFromContext(ctx context.Context) *coredata.PersonalAPIKey { - apiKey, _ := ctx.Value(apiKeyContextKey).(*coredata.PersonalAPIKey) - return apiKey -} - func NewAPIKeyMiddleware(svc *iam.Service, tokenSecret string) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc( @@ -95,8 +84,8 @@ func NewAPIKeyMiddleware(svc *iam.Service, tokenSecret string) func(next http.Ha panic(fmt.Errorf("cannot get identity: %w", err)) } - ctx = context.WithValue(ctx, apiKeyContextKey, apiKey) - ctx = context.WithValue(ctx, identityContextKey, identity) + ctx = ContextWithAPIKey(ctx, apiKey) + ctx = ContextWithIdentity(ctx, identity) next.ServeHTTP(w, r.WithContext(ctx)) }, diff --git a/pkg/server/api/authn/context.go b/pkg/server/api/authn/context.go new file mode 100644 index 000000000..54731fb92 --- /dev/null +++ b/pkg/server/api/authn/context.go @@ -0,0 +1,58 @@ +// Copyright (c) 2025 Probo Inc . +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +// PERFORMANCE OF THIS SOFTWARE. + +package authn + +import ( + "context" + + "go.probo.inc/probo/pkg/coredata" +) + +type ( + ctxKey struct{ name string } +) + +var ( + identityContextKey = &ctxKey{name: "identity"} + sessionContextKey = &ctxKey{name: "session"} + apiKeyContextKey = &ctxKey{name: "api_key"} +) + +func SessionFromContext(ctx context.Context) *coredata.Session { + session, _ := ctx.Value(sessionContextKey).(*coredata.Session) + return session +} + +func ContextWithSession(ctx context.Context, session *coredata.Session) context.Context { + return context.WithValue(ctx, sessionContextKey, session) +} + +func IdentityFromContext(ctx context.Context) *coredata.Identity { + identity, _ := ctx.Value(identityContextKey).(*coredata.Identity) + return identity +} + +func ContextWithIdentity(ctx context.Context, identity *coredata.Identity) context.Context { + return context.WithValue(ctx, identityContextKey, identity) +} + +func APIKeyFromContext(ctx context.Context) *coredata.PersonalAPIKey { + apiKey, _ := ctx.Value(apiKeyContextKey).(*coredata.PersonalAPIKey) + return apiKey +} + +func ContextWithAPIKey(ctx context.Context, apiKey *coredata.PersonalAPIKey) context.Context { + return context.WithValue(ctx, apiKeyContextKey, apiKey) +} diff --git a/pkg/server/api/connect/v1/identity_presence_middleware.go b/pkg/server/api/authn/identity_presence_middleware.go similarity index 98% rename from pkg/server/api/connect/v1/identity_presence_middleware.go rename to pkg/server/api/authn/identity_presence_middleware.go index 3b8555c9b..7a6d79eda 100644 --- a/pkg/server/api/connect/v1/identity_presence_middleware.go +++ b/pkg/server/api/authn/identity_presence_middleware.go @@ -12,7 +12,7 @@ // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. -package connect_v1 +package authn import ( "net/http" diff --git a/pkg/server/api/connect/v1/session_middleware.go b/pkg/server/api/authn/session_middleware.go similarity index 85% rename from pkg/server/api/connect/v1/session_middleware.go rename to pkg/server/api/authn/session_middleware.go index 5a57eaa21..22db2b40c 100644 --- a/pkg/server/api/connect/v1/session_middleware.go +++ b/pkg/server/api/authn/session_middleware.go @@ -12,10 +12,9 @@ // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. -package connect_v1 +package authn import ( - "context" "errors" "fmt" "net" @@ -24,28 +23,12 @@ import ( "github.com/99designs/gqlgen/graphql" "github.com/vektah/gqlparser/v2/gqlerror" "go.gearno.de/kit/httpserver" - "go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/securecookie" "go.probo.inc/probo/pkg/server/gqlutils" ) -var ( - identityContextKey = &ctxKey{name: "identity"} - sessionContextKey = &ctxKey{name: "session"} -) - -func SessionFromContext(ctx context.Context) *coredata.Session { - session, _ := ctx.Value(sessionContextKey).(*coredata.Session) - return session -} - -func IdentityFromContext(ctx context.Context) *coredata.Identity { - identity, _ := ctx.Value(identityContextKey).(*coredata.Identity) - return identity -} - func NewSessionMiddleware(svc *iam.Service, cookieConfig securecookie.Config) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc( @@ -119,8 +102,8 @@ func NewSessionMiddleware(svc *iam.Service, cookieConfig securecookie.Config) fu panic(fmt.Errorf("cannot update session info: %w", err)) } - ctx = context.WithValue(ctx, sessionContextKey, session) - ctx = context.WithValue(ctx, identityContextKey, identity) + ctx = ContextWithSession(ctx, session) + ctx = ContextWithIdentity(ctx, identity) next.ServeHTTP(w, r.WithContext(ctx)) diff --git a/pkg/server/api/connect/v1/authorization.go b/pkg/server/api/authz/authorization.go similarity index 93% rename from pkg/server/api/connect/v1/authorization.go rename to pkg/server/api/authz/authorization.go index 8f3f4fe90..442dd73e1 100644 --- a/pkg/server/api/connect/v1/authorization.go +++ b/pkg/server/api/authz/authorization.go @@ -12,7 +12,7 @@ // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. -package connect_v1 +package authz import ( "context" @@ -21,6 +21,7 @@ import ( "go.gearno.de/kit/log" "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" + "go.probo.inc/probo/pkg/server/api/authn" "go.probo.inc/probo/pkg/server/gqlutils" ) @@ -51,8 +52,8 @@ func NewAuthorizeFunc( action string, options ...AuthorizeFuncOption, ) error { - identity := IdentityFromContext(ctx) - session := SessionFromContext(ctx) + identity := authn.IdentityFromContext(ctx) + session := authn.SessionFromContext(ctx) params := iam.AuthorizeParams{ Principal: identity.ID, diff --git a/pkg/server/api/connect/v1/ctxkey.go b/pkg/server/api/connect/v1/ctxkey.go deleted file mode 100644 index 08bfd4432..000000000 --- a/pkg/server/api/connect/v1/ctxkey.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2025 Probo Inc . -// -// Permission to use, copy, modify, and/or distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -// PERFORMANCE OF THIS SOFTWARE. - -package connect_v1 - -type ( - ctxKey struct{ name string } -) diff --git a/pkg/server/api/connect/v1/graphql_handler.go b/pkg/server/api/connect/v1/graphql_handler.go index 559d69d30..6f0788ccd 100644 --- a/pkg/server/api/connect/v1/graphql_handler.go +++ b/pkg/server/api/connect/v1/graphql_handler.go @@ -23,14 +23,16 @@ import ( "go.probo.inc/probo/pkg/baseurl" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/securecookie" + "go.probo.inc/probo/pkg/server/api/authn" + "go.probo.inc/probo/pkg/server/api/authz" "go.probo.inc/probo/pkg/server/api/connect/v1/schema" "go.probo.inc/probo/pkg/server/api/connect/v1/types" "go.probo.inc/probo/pkg/server/gqlutils" ) func SessionDirective(ctx context.Context, obj any, next graphql.Resolver, required types.SessionRequirement) (any, error) { - session := SessionFromContext(ctx) - apiKey := APIKeyFromContext(ctx) + session := authn.SessionFromContext(ctx) + apiKey := authn.APIKeyFromContext(ctx) switch required { case types.SessionRequirementOptional: @@ -56,7 +58,7 @@ func SessionDirective(ctx context.Context, obj any, next graphql.Resolver, requi func NewGraphQLHandler(svc *iam.Service, logger *log.Logger, baseURL *baseurl.BaseURL, cookieConfig securecookie.Config) http.Handler { config := schema.Config{ Resolvers: &Resolver{ - authorize: NewAuthorizeFunc(svc, logger), + authorize: authz.NewAuthorizeFunc(svc, logger), logger: logger, iam: svc, baseURL: baseURL, diff --git a/pkg/server/api/connect/v1/resolver.go b/pkg/server/api/connect/v1/resolver.go index 824d65b1b..e74215b56 100644 --- a/pkg/server/api/connect/v1/resolver.go +++ b/pkg/server/api/connect/v1/resolver.go @@ -26,12 +26,15 @@ import ( "go.probo.inc/probo/pkg/baseurl" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/securecookie" + "go.probo.inc/probo/pkg/server/api/authn" + "go.probo.inc/probo/pkg/server/api/authz" "go.probo.inc/probo/pkg/server/api/connect/v1/types" + "go.probo.inc/probo/pkg/server/gqlutils" ) type ( Resolver struct { - authorize AuthorizeFunc + authorize authz.AuthorizeFunc logger *log.Logger iam *iam.Service baseURL *baseurl.BaseURL @@ -55,10 +58,10 @@ func (r *Resolver) sessionCookieConfig(maxAge time.Duration) securecookie.Config func NewMux(logger *log.Logger, svc *iam.Service, cookieConfig securecookie.Config, tokenSecret string, baseURL *baseurl.BaseURL) *chi.Mux { r := chi.NewMux() - r.Use(HTTPContextMiddleware) + r.Use(gqlutils.HTTPContextMiddleware) - sessionMiddleware := NewSessionMiddleware(svc, cookieConfig) - apiKeyMiddleware := NewAPIKeyMiddleware(svc, tokenSecret) + sessionMiddleware := authn.NewSessionMiddleware(svc, cookieConfig) + apiKeyMiddleware := authn.NewAPIKeyMiddleware(svc, tokenSecret) graphqlHandler := NewGraphQLHandler(svc, logger, baseURL, cookieConfig) samlHandler := NewSAMLHandler(svc, cookieConfig, baseURL, logger) scimHandler := NewSCIMHandler(svc, logger.Named("scim")) diff --git a/pkg/server/api/connect/v1/saml_handler.go b/pkg/server/api/connect/v1/saml_handler.go index 234a7c869..143936888 100644 --- a/pkg/server/api/connect/v1/saml_handler.go +++ b/pkg/server/api/connect/v1/saml_handler.go @@ -12,6 +12,7 @@ import ( "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/securecookie" + "go.probo.inc/probo/pkg/server/api/authn" ) type SAMLHandler struct { @@ -64,7 +65,7 @@ func (h *SAMLHandler) ConsumeHandler(w http.ResponseWriter, r *http.Request) { return } - rootSession := SessionFromContext(ctx) + rootSession := authn.SessionFromContext(ctx) switch { case rootSession == nil: diff --git a/pkg/server/api/connect/v1/scim_handler.go b/pkg/server/api/connect/v1/scim_handler.go index a019568b4..67891340f 100644 --- a/pkg/server/api/connect/v1/scim_handler.go +++ b/pkg/server/api/connect/v1/scim_handler.go @@ -34,6 +34,8 @@ import ( ) type ( + ctxKey struct{ name string } + SCIMHandler struct { iam *iam.Service logger *log.Logger diff --git a/pkg/server/api/connect/v1/v1_resolver.go b/pkg/server/api/connect/v1/v1_resolver.go index d7a1eafce..a51fb46a1 100644 --- a/pkg/server/api/connect/v1/v1_resolver.go +++ b/pkg/server/api/connect/v1/v1_resolver.go @@ -20,6 +20,8 @@ import ( "go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/securecookie" + "go.probo.inc/probo/pkg/server/api/authn" + "go.probo.inc/probo/pkg/server/api/authz" "go.probo.inc/probo/pkg/server/api/connect/v1/schema" "go.probo.inc/probo/pkg/server/api/connect/v1/types" "go.probo.inc/probo/pkg/server/gqlutils" @@ -223,7 +225,7 @@ func (r *membershipResolver) Identity(ctx context.Context, obj *types.Membership ctx, obj.Identity.ID, iam.ActionIdentityGet, - WithAttr("organization_id", obj.Organization.ID.String()), + authz.WithAttr("organization_id", obj.Organization.ID.String()), ); err != nil { return nil, err } @@ -271,7 +273,7 @@ func (r *membershipResolver) Profile(ctx context.Context, obj *types.Membership) // Organization is the resolver for the organization field. func (r *membershipResolver) Organization(ctx context.Context, obj *types.Membership) (*types.Organization, error) { - if err := r.authorize(ctx, obj.Organization.ID, iam.ActionOrganizationGet, WithSession(nil)); err != nil { + if err := r.authorize(ctx, obj.Organization.ID, iam.ActionOrganizationGet, authz.WithSession(nil)); err != nil { return nil, err } @@ -292,11 +294,11 @@ func (r *membershipResolver) Organization(ctx context.Context, obj *types.Member // LastSession is the resolver for the lastSession field. func (r *membershipResolver) LastSession(ctx context.Context, obj *types.Membership) (*types.Session, error) { - if err := r.authorize(ctx, obj.ID, iam.ActionMembershipGet, WithSession(nil)); err != nil { + if err := r.authorize(ctx, obj.ID, iam.ActionMembershipGet, authz.WithSession(nil)); err != nil { return nil, err } - session := SessionFromContext(ctx) + session := authn.SessionFromContext(ctx) if session == nil { return nil, nil } @@ -379,7 +381,7 @@ func (r *mutationResolver) SignIn(ctx context.Context, input types.SignInInput) return nil, gqlutils.Internal(ctx) } - w := HTTPResponseWriterFromContext(ctx) + w := gqlutils.HTTPResponseWriterFromContext(ctx) securecookie.Set( w, r.sessionCookieConfig(time.Until(session.ExpiredAt)), @@ -412,7 +414,7 @@ func (r *mutationResolver) SignUp(ctx context.Context, input types.SignUpInput) return nil, gqlutils.Internal(ctx) } - w := HTTPResponseWriterFromContext(ctx) + w := gqlutils.HTTPResponseWriterFromContext(ctx) securecookie.Set( w, r.sessionCookieConfig(time.Until(session.ExpiredAt)), @@ -426,7 +428,7 @@ func (r *mutationResolver) SignUp(ctx context.Context, input types.SignUpInput) // SignOut is the resolver for the signOut field. func (r *mutationResolver) SignOut(ctx context.Context) (*types.SignOutPayload, error) { - session := SessionFromContext(ctx) + session := authn.SessionFromContext(ctx) err := r.iam.SessionService.CloseSession(ctx, session.ID) if err != nil { @@ -478,7 +480,7 @@ func (r *mutationResolver) SignUpFromInvitation(ctx context.Context, input types return nil, gqlutils.Internal(ctx) } - w := HTTPResponseWriterFromContext(ctx) + w := gqlutils.HTTPResponseWriterFromContext(ctx) securecookie.Set( w, r.sessionCookieConfig(time.Until(session.ExpiredAt)), @@ -573,7 +575,7 @@ func (r *mutationResolver) VerifyEmail(ctx context.Context, input types.VerifyEm // ChangePassword is the resolver for the changePassword field. func (r *mutationResolver) ChangePassword(ctx context.Context, input types.ChangePasswordInput) (*types.ChangePasswordPayload, error) { - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) err := r.iam.AccountService.ChangePassword( ctx, @@ -608,7 +610,7 @@ func (r *mutationResolver) ChangePassword(ctx context.Context, input types.Chang // ChangeEmail is the resolver for the changeEmail field. func (r *mutationResolver) ChangeEmail(ctx context.Context, input types.ChangeEmailInput) (*types.ChangeEmailPayload, error) { - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) err := r.iam.AccountService.ChangeEmail( ctx, @@ -643,7 +645,7 @@ func (r *mutationResolver) ChangeEmail(ctx context.Context, input types.ChangeEm // AssumeOrganizationSession is the resolver for the assumeOrganizationSession field. func (r *mutationResolver) AssumeOrganizationSession(ctx context.Context, input types.AssumeOrganizationSessionInput) (*types.AssumeOrganizationSessionPayload, error) { - rootSession := SessionFromContext(ctx) + rootSession := authn.SessionFromContext(ctx) childSession, membership, err := r.iam.SessionService.AssumeOrganizationSession(ctx, rootSession.ID, input.OrganizationID) if err != nil { @@ -692,7 +694,7 @@ func (r *mutationResolver) RevokeSession(ctx context.Context, input types.Revoke return nil, err } - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) err := r.iam.SessionService.RevokeSession(ctx, identity.ID, input.SessionID) if err != nil { @@ -710,11 +712,11 @@ func (r *mutationResolver) RevokeSession(ctx context.Context, input types.Revoke // RevokeAllSessions is the resolver for the revokeAllSessions field. func (r *mutationResolver) RevokeAllSessions(ctx context.Context) (*types.RevokeAllSessionsPayload, error) { - if err := r.authorize(ctx, SessionFromContext(ctx).ID, iam.ActionSessionRevokeAll); err != nil { + if err := r.authorize(ctx, authn.SessionFromContext(ctx).ID, iam.ActionSessionRevokeAll); err != nil { return nil, err } - session := SessionFromContext(ctx) + session := authn.SessionFromContext(ctx) revokedCount, err := r.iam.SessionService.RevokeAllSessions(ctx, session.ID) if err != nil { @@ -727,7 +729,7 @@ func (r *mutationResolver) RevokeAllSessions(ctx context.Context) (*types.Revoke // CreatePersonalAPIKey is the resolver for the createPersonalAPIKey field. func (r *mutationResolver) CreatePersonalAPIKey(ctx context.Context, input types.CreatePersonalAPIKeyInput) (*types.CreatePersonalAPIKeyPayload, error) { - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) if err := r.authorize(ctx, identity.ID, iam.ActionPersonalAPIKeyCreate); err != nil { return nil, err @@ -756,7 +758,7 @@ func (r *mutationResolver) RevokePersonalAPIKey(ctx context.Context, input types return nil, err } - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) err := r.iam.AccountService.DeletePersonalAPIKey(ctx, identity.ID, input.PersonalAPIKeyID) if err != nil { @@ -769,7 +771,7 @@ func (r *mutationResolver) RevokePersonalAPIKey(ctx context.Context, input types // CreateOrganization is the resolver for the createOrganization field. func (r *mutationResolver) CreateOrganization(ctx context.Context, input types.CreateOrganizationInput) (*types.CreateOrganizationPayload, error) { - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) // FIXME check email domain and related IDP config // if ok := r.authorize(ctx, identity.ID, iam.ActionOrganizationCreate); !ok { @@ -1004,7 +1006,7 @@ func (r *mutationResolver) AcceptInvitation(ctx context.Context, input types.Acc return nil, err } - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) invitation, membership, err := r.iam.AccountService.AcceptInvitation(ctx, identity.ID, input.InvitationID) if err != nil { @@ -1168,7 +1170,7 @@ func (r *mutationResolver) RegenerateSCIMToken(ctx context.Context, input types. // LogoURL is the resolver for the logoUrl field. func (r *organizationResolver) LogoURL(ctx context.Context, obj *types.Organization) (*string, error) { - if err := r.authorize(ctx, obj.ID, iam.ActionOrganizationGet, WithSession(nil)); err != nil { + if err := r.authorize(ctx, obj.ID, iam.ActionOrganizationGet, authz.WithSession(nil)); err != nil { return nil, err } @@ -1321,11 +1323,11 @@ func (r *organizationResolver) ScimConfiguration(ctx context.Context, obj *types // ViewerMembership is the resolver for the viewerMembership field. func (r *organizationResolver) ViewerMembership(ctx context.Context, obj *types.Organization) (*types.Membership, error) { - if err := r.authorize(ctx, obj.ID, iam.ActionMembershipGet, WithSession(nil)); err != nil { + if err := r.authorize(ctx, obj.ID, iam.ActionMembershipGet, authz.WithSession(nil)); err != nil { return nil, err } - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) membership, err := r.iam.AccountService.GetMembershipForOrganization(ctx, identity.ID, obj.ID) if err != nil { @@ -1347,7 +1349,7 @@ func (r *personalAPIKeyResolver) Token(ctx context.Context, obj *types.PersonalA return nil, err } - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) token, err := r.iam.AccountService.RevealPersonalAPIKeyToken(ctx, identity.ID, obj.ID) if err != nil { @@ -1515,7 +1517,7 @@ func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error // Viewer is the resolver for the viewer field. func (r *queryResolver) Viewer(ctx context.Context) (*types.Identity, error) { - identity := IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) return &types.Identity{ ID: identity.ID, diff --git a/pkg/server/api/console/v1/graphql_handler.go b/pkg/server/api/console/v1/graphql_handler.go index 4de50f234..53242be45 100644 --- a/pkg/server/api/console/v1/graphql_handler.go +++ b/pkg/server/api/console/v1/graphql_handler.go @@ -20,7 +20,7 @@ import ( "go.gearno.de/kit/log" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/probo" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authz" "go.probo.inc/probo/pkg/server/api/console/v1/schema" "go.probo.inc/probo/pkg/server/gqlutils" ) @@ -28,7 +28,7 @@ import ( func NewGraphQLHandler(iamSvc *iam.Service, proboSvc *probo.Service, customDomainCname string, logger *log.Logger) http.Handler { config := schema.Config{ Resolvers: &Resolver{ - authorize: connect_v1.NewAuthorizeFunc(iamSvc, logger), + authorize: authz.NewAuthorizeFunc(iamSvc, logger), probo: proboSvc, iam: iamSvc, customDomainCname: customDomainCname, diff --git a/pkg/server/api/console/v1/resolver.go b/pkg/server/api/console/v1/resolver.go index 597b61f1e..f1e9906ce 100644 --- a/pkg/server/api/console/v1/resolver.go +++ b/pkg/server/api/console/v1/resolver.go @@ -35,14 +35,15 @@ import ( "go.probo.inc/probo/pkg/probo" "go.probo.inc/probo/pkg/saferedirect" "go.probo.inc/probo/pkg/securecookie" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" + "go.probo.inc/probo/pkg/server/api/authz" "go.probo.inc/probo/pkg/server/api/console/v1/types" "go.probo.inc/probo/pkg/statelesstoken" ) type ( Resolver struct { - authorize connect_v1.AuthorizeFunc + authorize authz.AuthorizeFunc probo *probo.Service iam *iam.Service customDomainCname string @@ -63,9 +64,9 @@ func NewMux( safeRedirect := &saferedirect.SafeRedirect{AllowedHost: baseURL.Host()} - r.Use(connect_v1.NewSessionMiddleware(iamSvc, cookieConfig)) - r.Use(connect_v1.NewAPIKeyMiddleware(iamSvc, tokenSecret)) - r.Use(connect_v1.NewIdentityPresenceMiddleware()) + r.Use(authn.NewSessionMiddleware(iamSvc, cookieConfig)) + r.Use(authn.NewAPIKeyMiddleware(iamSvc, tokenSecret)) + r.Use(authn.NewIdentityPresenceMiddleware()) graphqlHandler := NewGraphQLHandler(iamSvc, proboSvc, customDomainCname, logger) @@ -199,18 +200,18 @@ func NewMux( panic(fmt.Errorf("cannot parse organization id: %w", err)) } - apiKey := connect_v1.APIKeyFromContext(r.Context()) + apiKey := authn.APIKeyFromContext(r.Context()) if apiKey != nil { httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("api key authentication cannot be used for this endpoint")) return } - identity := connect_v1.IdentityFromContext(r.Context()) + identity := authn.IdentityFromContext(r.Context()) if identity == nil { httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required")) return } - session := connect_v1.SessionFromContext(r.Context()) + session := authn.SessionFromContext(r.Context()) if session == nil { httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required")) return diff --git a/pkg/server/api/console/v1/v1_resolver.go b/pkg/server/api/console/v1/v1_resolver.go index 3798cee7c..4452ca20d 100644 --- a/pkg/server/api/console/v1/v1_resolver.go +++ b/pkg/server/api/console/v1/v1_resolver.go @@ -19,7 +19,7 @@ import ( "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/probo" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" "go.probo.inc/probo/pkg/server/api/console/v1/schema" "go.probo.inc/probo/pkg/server/api/console/v1/types" "go.probo.inc/probo/pkg/server/gqlutils" @@ -1037,7 +1037,7 @@ func (r *documentVersionResolver) Signed(ctx context.Context, obj *types.Documen return false, err } - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) prb := r.ProboService(ctx, obj.ID.TenantID()) @@ -2419,7 +2419,7 @@ func (r *mutationResolver) ExportFramework(ctx context.Context, input types.Expo } prb := r.ProboService(ctx, input.FrameworkID.TenantID()) - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) exportErr, exportJobID := prb.Frameworks.RequestExport( ctx, @@ -3681,7 +3681,7 @@ func (r *mutationResolver) PublishDocumentVersion(ctx context.Context, input typ prb := r.ProboService(ctx, input.DocumentID.TenantID()) - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) document, documentVersion, err := prb.Documents.PublishVersion(ctx, input.DocumentID, identity.ID, input.Changelog) if err != nil { @@ -3717,7 +3717,7 @@ func (r *mutationResolver) BulkPublishDocumentVersions(ctx context.Context, inpu prb := r.ProboService(ctx, input.DocumentIds[0].TenantID()) - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) documentVersions, documents, err := prb.Documents.BulkPublishVersions( ctx, @@ -3784,7 +3784,7 @@ func (r *mutationResolver) BulkExportDocuments(ctx context.Context, input types. prb := r.ProboService(ctx, input.DocumentIds[0].TenantID()) - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) options := probo.ExportPDFOptions{ WithWatermark: input.WithWatermark, @@ -3986,7 +3986,7 @@ func (r *mutationResolver) SignDocument(ctx context.Context, input types.SignDoc return nil, err } - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) prb := r.ProboService(ctx, input.DocumentVersionID.TenantID()) documentVersionSignature, err := prb.Documents.SignDocumentVersionByEmail(ctx, input.DocumentVersionID, identity.EmailAddress) @@ -4043,7 +4043,7 @@ func (r *mutationResolver) ExportSignableVersionDocumentPDF(ctx context.Context, panic(fmt.Errorf("cannot get document version: %w", err)) } - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) documentFilter := coredata.NewDocumentFilter(nil).WithUserEmail(&identity.EmailAddress) _, err = prb.Documents.GetWithFilter(ctx, documentVersion.DocumentID, documentFilter) @@ -6689,10 +6689,10 @@ func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error // Viewer is the resolver for the viewer field. func (r *queryResolver) Viewer(ctx context.Context) (*types.Viewer, error) { - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) - session := connect_v1.SessionFromContext(ctx) - apiKey := connect_v1.APIKeyFromContext(ctx) + session := authn.SessionFromContext(ctx) + apiKey := authn.APIKeyFromContext(ctx) var viewerID gid.GID if session != nil { @@ -7020,7 +7020,7 @@ func (r *signableDocumentResolver) Signed(ctx context.Context, obj *types.Signab return false, err } - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) prb := r.ProboService(ctx, obj.ID.TenantID()) @@ -7053,7 +7053,7 @@ func (r *signableDocumentResolver) Versions(ctx context.Context, obj *types.Sign cursor := types.NewCursor(first, after, last, before, pageOrderBy) - user := connect_v1.IdentityFromContext(ctx) + user := authn.IdentityFromContext(ctx) versionFilter := coredata.NewDocumentVersionFilter().WithUserEmail(&user.EmailAddress) @@ -8350,7 +8350,7 @@ func (r *viewerResolver) SignableDocuments(ctx context.Context, obj *types.Viewe cursor := types.NewCursor(first, after, last, before, pageOrderBy) - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) documentFilter := coredata.NewDocumentFilter(nil).WithUserEmail(&identity.EmailAddress) @@ -8384,7 +8384,7 @@ func (r *viewerResolver) SignableDocument(ctx context.Context, obj *types.Viewer prb := r.ProboService(ctx, id.TenantID()) - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) documentFilter := coredata.NewDocumentFilter(nil).WithUserEmail(&identity.EmailAddress) document, err := prb.Documents.GetWithFilter(ctx, id, documentFilter) diff --git a/pkg/server/api/mcp/v1/middleware.go b/pkg/server/api/mcp/v1/middleware.go index ea43ca73f..6be991012 100644 --- a/pkg/server/api/mcp/v1/middleware.go +++ b/pkg/server/api/mcp/v1/middleware.go @@ -21,7 +21,7 @@ import ( "go.gearno.de/kit/httpserver" "go.gearno.de/kit/log" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" ) func RequireAPIKeyHandler( @@ -40,8 +40,8 @@ func RequireAPIKeyHandler( log.String("path", r.URL.Path), ) - apiKey := connect_v1.APIKeyFromContext(ctx) - identity := connect_v1.IdentityFromContext(ctx) + apiKey := authn.APIKeyFromContext(ctx) + identity := authn.IdentityFromContext(ctx) if identity == nil { httpserver.RenderError(w, http.StatusUnauthorized, errors.New("authentication required")) return diff --git a/pkg/server/api/mcp/v1/resolver.go b/pkg/server/api/mcp/v1/resolver.go index 05276c372..abe814938 100644 --- a/pkg/server/api/mcp/v1/resolver.go +++ b/pkg/server/api/mcp/v1/resolver.go @@ -9,7 +9,7 @@ import ( "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/probo" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" ) type Resolver struct { @@ -19,7 +19,7 @@ type Resolver struct { } func (r *Resolver) MustAuthorize(ctx context.Context, entityID gid.GID, action iam.Action) { - identity := connect_v1.IdentityFromContext(ctx) + identity := authn.IdentityFromContext(ctx) err := r.iamSvc.Authorizer.Authorize( ctx, diff --git a/pkg/server/api/mcp/v1/schema.resolvers.go b/pkg/server/api/mcp/v1/schema.resolvers.go index fe080e5f1..ab81990a6 100644 --- a/pkg/server/api/mcp/v1/schema.resolvers.go +++ b/pkg/server/api/mcp/v1/schema.resolvers.go @@ -13,14 +13,14 @@ import ( "go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/probo" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" "go.probo.inc/probo/pkg/server/api/mcp/v1/types" ) // ListOrganizationsTool handles the listOrganizations tool // List all organizations the user has access to func (r *Resolver) ListOrganizationsTool(ctx context.Context, req *mcp.CallToolRequest, input *types.ListOrganizationsInput) (*mcp.CallToolResult, types.ListOrganizationsOutput, error) { - user := connect_v1.IdentityFromContext(ctx) + user := authn.IdentityFromContext(ctx) organizations, err := r.iamSvc.AccountService.ListOrganizations(ctx, user.ID) if err != nil { @@ -1686,7 +1686,7 @@ func (r *Resolver) PublishDocumentVersionTool(ctx context.Context, req *mcp.Call svc := r.ProboService(ctx, input.DocumentID) - user := connect_v1.IdentityFromContext(ctx) + user := authn.IdentityFromContext(ctx) document, documentVersion, err := svc.Documents.PublishVersion(ctx, input.DocumentID, user.ID, input.Changelog) if err != nil { diff --git a/pkg/server/api/mcp/v1/v1_handler.go b/pkg/server/api/mcp/v1/v1_handler.go index de36c443c..5b794d455 100644 --- a/pkg/server/api/mcp/v1/v1_handler.go +++ b/pkg/server/api/mcp/v1/v1_handler.go @@ -11,7 +11,7 @@ import ( "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/probo" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" "go.probo.inc/probo/pkg/server/api/mcp/mcputils" "go.probo.inc/probo/pkg/server/api/mcp/v1/server" ) @@ -52,7 +52,7 @@ func NewMux(logger *log.Logger, proboSvc *probo.Service, iamSvc *iam.Service, to ) r := chi.NewMux() - r.Use(connect_v1.NewAPIKeyMiddleware(iamSvc, tokenSecret)) + r.Use(authn.NewAPIKeyMiddleware(iamSvc, tokenSecret)) r.Handle("/", RequireAPIKeyHandler(logger, handler)) logger.Info("MCP server initialized successfully") diff --git a/pkg/server/api/trust/v1/resolver.go b/pkg/server/api/trust/v1/resolver.go index 8e1298abb..22f5c3be2 100644 --- a/pkg/server/api/trust/v1/resolver.go +++ b/pkg/server/api/trust/v1/resolver.go @@ -25,7 +25,7 @@ import ( "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/securecookie" - connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1" + "go.probo.inc/probo/pkg/server/api/authn" "go.probo.inc/probo/pkg/server/api/trust/v1/schema" "go.probo.inc/probo/pkg/server/gqlutils" "go.probo.inc/probo/pkg/trust" @@ -57,7 +57,7 @@ func NewMux( ) *chi.Mux { r := chi.NewMux() - sessionMiddleware := connect_v1.NewSessionMiddleware(iamSvc, cookieConfig) + sessionMiddleware := authn.NewSessionMiddleware(iamSvc, cookieConfig) r.Use(sessionMiddleware) config := schema.Config{Resolvers: &Resolver{trust: trustSvc}} diff --git a/pkg/server/api/connect/v1/httpctx.go b/pkg/server/gqlutils/httpctx.go similarity index 96% rename from pkg/server/api/connect/v1/httpctx.go rename to pkg/server/gqlutils/httpctx.go index 99a0f8192..6253bd659 100644 --- a/pkg/server/api/connect/v1/httpctx.go +++ b/pkg/server/gqlutils/httpctx.go @@ -12,13 +12,17 @@ // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. -package connect_v1 +package gqlutils import ( "context" "net/http" ) +type ( + ctxKey struct{ name string } +) + var ( httpResponseWriterKey = &ctxKey{name: "http_response_writer"} httpRequestKey = &ctxKey{name: "http_request"}