From dda6104722308169a3bdea38cd3ffd6fdda13034 Mon Sep 17 00:00:00 2001 From: Julian Koberg Date: Thu, 18 Sep 2025 16:17:04 +0200 Subject: [PATCH] feat: document mfa package Signed-off-by: Julian Koberg --- ocis-pkg/mfa/mfa.go | 44 ++++++------ ocis-pkg/mfa/mfa_test.go | 71 ++++++++++++++++++++ services/frontend/pkg/config/config.go | 2 +- services/graph/pkg/middleware/auth.go | 4 +- services/graph/pkg/service/v0/drives.go | 8 ++- services/graph/pkg/service/v0/graph_test.go | 1 + services/graph/pkg/service/v0/groups.go | 3 +- services/graph/pkg/service/v0/groups_test.go | 1 + services/graph/pkg/service/v0/users.go | 3 +- services/graph/pkg/service/v0/users_test.go | 1 + services/proxy/README.md | 11 +-- services/proxy/pkg/config/config.go | 2 +- services/proxy/pkg/middleware/mfa.go | 3 + 13 files changed, 122 insertions(+), 32 deletions(-) create mode 100644 ocis-pkg/mfa/mfa_test.go diff --git a/ocis-pkg/mfa/mfa.go b/ocis-pkg/mfa/mfa.go index 3f38cd32411..f1b1bc67e5b 100644 --- a/ocis-pkg/mfa/mfa.go +++ b/ocis-pkg/mfa/mfa.go @@ -1,4 +1,5 @@ // Package mfa provides functionality for multi-factor authentication (MFA). +// mfa_test.go contains usage examples and tests. package mfa import ( @@ -17,22 +18,33 @@ type mfaKeyType struct{} var mfaKey = mfaKeyType{} -// FromRequest extracts the mfa status from the request headers -func FromRequest(ctx context.Context, req *http.Request) context.Context { - return Set(ctx, req.Header.Get(MFAHeader) == "true") -} - -// Accepted checks if the context has MFA authentication. If not, it sets the required header and status code. -func Accepted(ctx context.Context, w http.ResponseWriter) bool { - hasMFA := Has(ctx) - if !hasMFA { - SetRequiredHeader(w) +// EnhanceRequest enhances the request context with the MFA status from the header. +// This operation does not overwrite existing context values. +func EnhanceRequest(req *http.Request) *http.Request { + ctx := req.Context() + if Get(ctx) { + return req } - return hasMFA + return req.WithContext(Set(ctx, req.Header.Get(MFAHeader) == "true")) } -// Has returns true if the user is MFA authenticated. -func Has(ctx context.Context) bool { +// EnsureOrReject sets the MFA required header and status code 403 if not multi factor authenticated. +func EnsureOrReject(ctx context.Context, w http.ResponseWriter) (hasMFA bool) { + hasMFA = Get(ctx) + if !hasMFA { + SetRequiredStatus(w) + } + return +} + +// SetRequiredStatus sets the MFA required header and the statuscode to 403 +func SetRequiredStatus(w http.ResponseWriter) { + w.Header().Set(MFARequiredHeader, "true") + w.WriteHeader(http.StatusForbidden) +} + +// Get gets the mfa status from the context. +func Get(ctx context.Context) bool { mfa, ok := ctx.Value(mfaKey).(bool) if !ok { return false @@ -54,9 +66,3 @@ func SetHeader(r *http.Request, mfa bool) { r.Header.Set(MFAHeader, "false") } - -// SetRequiredHeader sets the MFA required header and the statuscode to 403 -func SetRequiredHeader(w http.ResponseWriter) { - w.Header().Set(MFARequiredHeader, "true") - w.WriteHeader(http.StatusForbidden) -} diff --git a/ocis-pkg/mfa/mfa_test.go b/ocis-pkg/mfa/mfa_test.go new file mode 100644 index 00000000000..f43815e737d --- /dev/null +++ b/ocis-pkg/mfa/mfa_test.go @@ -0,0 +1,71 @@ +package mfa_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" + "github.com/test-go/testify/require" +) + +func exampleUsage() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // In a central place of your service enhance request once. + // Note: This will not overwrite existing context values so it's safe (but unnecessary) to call multiple times. + r = mfa.EnhanceRequest(r) + + // somewhere in your code extract the context + ctx := r.Context() + + // now you can check if the user has MFA enabled + hasMFA := mfa.Get(ctx) + _ = hasMFA // use it as needed + + // use convenience method to automatically set headers and response codes + if !mfa.EnsureOrReject(ctx, w) { + // use this line to log access denied information + // mfa package will not log anything by itself + return + } + // user has MFA enabled, you can now proceed with sensitive operation + } +} + +func TestMFALifecycle(t *testing.T) { + testCases := []struct { + Alias string + HasMFA bool + ShouldHaveMFA bool + ResponseCode int + }{ + { + Alias: "simple", + HasMFA: true, + ResponseCode: http.StatusOK, + }, + { + Alias: "denied", + HasMFA: false, + ResponseCode: http.StatusForbidden, + }, + } + + for _, tc := range testCases { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "http://url&method.doesnt.matter", nil) + mfa.SetHeader(r, tc.HasMFA) + + exampleUsage().ServeHTTP(w, r) + res := w.Result() + + require.Equal(t, tc.ResponseCode, res.StatusCode, tc.Alias) + if tc.ResponseCode == http.StatusForbidden { + require.Equal(t, "true", res.Header.Get(mfa.MFARequiredHeader), tc.Alias) + } else { + require.Empty(t, res.Header.Get(mfa.MFARequiredHeader), tc.Alias) + } + + } + +} diff --git a/services/frontend/pkg/config/config.go b/services/frontend/pkg/config/config.go index 68050c85522..6bbea1e91ad 100644 --- a/services/frontend/pkg/config/config.go +++ b/services/frontend/pkg/config/config.go @@ -206,5 +206,5 @@ type Validation struct { // MFAConfig configures multi factor multifactor authentication type MFAConfig struct { Enabled bool `yaml:"enabled" env:"OCIS_MFA_ENABLED" desc:"Set to true to enable multi factor authentication. See the documentation for more details." introductionVersion:"Balch"` - AuthLevelNames []string `yaml:"auth_level_names" env:"OCIS_MFA_AUTH_LEVEL_NAMES" desc:"A list of authentication level names that indicate that multi factor authentication has been performed. The names must match the acr claim in the access token. Web will use the first one in the list when requesting mfa." introductionVersion:"Balch"` + AuthLevelNames []string `yaml:"auth_level_names" env:"OCIS_MFA_AUTH_LEVEL_NAMES" desc:"This authentication level name indicates that multi-factor authentication was performed. The name must match the ACR claim in the access token received. Note: If multiple names are required, use a comma-separated list. The front-end service will use the first name in the list when requesting multi-factor authentication (MFA)." introductionVersion:"Balch"` } diff --git a/services/graph/pkg/middleware/auth.go b/services/graph/pkg/middleware/auth.go index 0cbfce89ded..3e382ec8d17 100644 --- a/services/graph/pkg/middleware/auth.go +++ b/services/graph/pkg/middleware/auth.go @@ -43,6 +43,8 @@ func Auth(opts ...account.Option) func(http.Handler) http.Handler { } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r = mfa.EnhanceRequest(r) + ctx := r.Context() t := r.Header.Get("x-access-token") if t == "" { @@ -91,8 +93,6 @@ func Auth(opts ...account.Option) func(http.Handler) http.Handler { ctx = metadata.AppendToOutgoingContext(ctx, ctxpkg.InitiatorHeader, initiatorID) } - ctx = mfa.FromRequest(ctx, r) - next.ServeHTTP(w, r.WithContext(ctx)) }) } diff --git a/services/graph/pkg/service/v0/drives.go b/services/graph/pkg/service/v0/drives.go index 32625f5bca0..e5aa3e77c35 100644 --- a/services/graph/pkg/service/v0/drives.go +++ b/services/graph/pkg/service/v0/drives.go @@ -133,7 +133,9 @@ func (g Graph) GetAllDrives(version APIVersion) http.HandlerFunc { // GetAllDrivesV1 attempts to retrieve the current users drives; // it includes another user's drives, if the current user has the permission. func (g Graph) GetAllDrivesV1(w http.ResponseWriter, r *http.Request) { - if !mfa.Accepted(r.Context(), w) { + if !mfa.EnsureOrReject(r.Context(), w) { + logger := g.logger.SubloggerWithRequestID(r.Context()) + logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied") return } @@ -157,7 +159,9 @@ func (g Graph) GetAllDrivesV1(w http.ResponseWriter, r *http.Request) { // it includes the grantedtoV2 property // it uses unified roles instead of the cs3 representations func (g Graph) GetAllDrivesV1Beta1(w http.ResponseWriter, r *http.Request) { - if !mfa.Accepted(r.Context(), w) { + if !mfa.EnsureOrReject(r.Context(), w) { + logger := g.logger.SubloggerWithRequestID(r.Context()) + logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied") return } diff --git a/services/graph/pkg/service/v0/graph_test.go b/services/graph/pkg/service/v0/graph_test.go index 4eea336a1f4..c065cb6aa81 100644 --- a/services/graph/pkg/service/v0/graph_test.go +++ b/services/graph/pkg/service/v0/graph_test.go @@ -140,6 +140,7 @@ var _ = Describe("Graph", func() { rr := httptest.NewRecorder() svc.GetAllDrivesV1(rr, r) Expect(rr.Code).To(Equal(http.StatusForbidden)) + Expect(rr.Header().Get("X-Ocis-Mfa-Required")).To(Equal("true")) }) It("can list a space without owner", func() { diff --git a/services/graph/pkg/service/v0/groups.go b/services/graph/pkg/service/v0/groups.go index 1cf715b208d..a81faa37c85 100644 --- a/services/graph/pkg/service/v0/groups.go +++ b/services/graph/pkg/service/v0/groups.go @@ -51,7 +51,8 @@ func (g Graph) GetGroups(w http.ResponseWriter, r *http.Request) { return } - if !mfa.Accepted(r.Context(), w) { + if !mfa.EnsureOrReject(r.Context(), w) { + logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied") return } } diff --git a/services/graph/pkg/service/v0/groups_test.go b/services/graph/pkg/service/v0/groups_test.go index 7ee94ce4cf7..a52bb4b6e13 100644 --- a/services/graph/pkg/service/v0/groups_test.go +++ b/services/graph/pkg/service/v0/groups_test.go @@ -230,6 +230,7 @@ var _ = Describe("Groups", func() { svc.GetGroups(rr, r) Expect(rr.Code).To(Equal(http.StatusForbidden)) + Expect(rr.Header().Get("X-Ocis-Mfa-Required")).To(Equal("true")) }) It("denies listing for unprivileged users", func() { permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{}, nil) diff --git a/services/graph/pkg/service/v0/users.go b/services/graph/pkg/service/v0/users.go index e4b8cf78b2a..5dad76424cd 100644 --- a/services/graph/pkg/service/v0/users.go +++ b/services/graph/pkg/service/v0/users.go @@ -239,7 +239,8 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) { errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "search term too short") return } - if !mfa.Accepted(r.Context(), w) { + if !mfa.EnsureOrReject(r.Context(), w) { + logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied") return } } diff --git a/services/graph/pkg/service/v0/users_test.go b/services/graph/pkg/service/v0/users_test.go index a4ba9983593..d15082cf513 100644 --- a/services/graph/pkg/service/v0/users_test.go +++ b/services/graph/pkg/service/v0/users_test.go @@ -283,6 +283,7 @@ var _ = Describe("Users", func() { svc.GetUsers(rr, r) Expect(rr.Code).To(Equal(http.StatusForbidden)) + Expect(rr.Header().Get("X-Ocis-Mfa-Required")).To(Equal("true")) }) It("denies listing for unprivileged users", func() { permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{}, nil) diff --git a/services/proxy/README.md b/services/proxy/README.md index 10147987a86..6b21d818586 100644 --- a/services/proxy/README.md +++ b/services/proxy/README.md @@ -146,18 +146,19 @@ These issued JWT tokens are immutable and integrity-protected. Which means, any * Infinite Scale does not get aware when a group is being deleted in the IDP, a new claim will not hold any information from the deleted group. Infinite Scale does not track a claim history to compare. -#### Claim checks and step up authentication +#### Claim Checks and Step-up Authentication + +Infinite Scale provides access control via the OpenID Connect (OIDC) "Authentication Class Reference" (ACR) claim. This can be used to enforce step-up authentication on specific routes. For instance, if a user logs in with basic authentication, they may need a higher level to access a sensitive route. If the user has not authenticated at the required level, access to the route will be denied. +This is configurable via environment variables, such as: -Infinite Scale can provide access control via the OIDC "acr" claim ("Authentication Class Reference"). This can be used to enforce step up authentication on specific routes. For example, a user might have logged in with a basic authentication level, but to access a sensitive route, a higher authentication level is required. If the user has not authenticated with the required level, access to the route will be denied. -Configurable via env variables: ``` OCIS_MFA_ENABLED: true OCIS_MFA_AUTH_LEVEL_NAME: advanced ``` -This feature is disabled by default, and requires an external IDP that supports step up authentication and the acr claim (e.g. Keycloak). +This feature is disabled by default and requires an external Identity Provider (IDP) that supports step-up authentication and the ACR claim. Examples of such IDPs include Keycloak. -When an authenticated user tries to access a protected route without 2FA, the server will respond with `403 Forbidden` and a `X-OCIS-MFA-Required` header. +If an authenticated user attempts to access a protected route without two-factor authentication (2FA), the server will respond with a 403 Forbidden error and an `X-OCIS-MFA-Required` header. #### Impacts diff --git a/services/proxy/pkg/config/config.go b/services/proxy/pkg/config/config.go index d2930aeb071..aca97af0934 100644 --- a/services/proxy/pkg/config/config.go +++ b/services/proxy/pkg/config/config.go @@ -129,7 +129,7 @@ type JWKS struct { type MFAConfig struct { Enabled bool `yaml:"enabled" env:"OCIS_MFA_ENABLED" desc:"Enable MFA enforcement. If enabled users need to complete MFA before they can access specific paths" introductionVersion:"Balch"` - AuthLevelNames []string `yaml:"auth_level_name" env:"OCIS_MFA_AUTH_LEVEL_NAMES" desc:"The names of the auth levels that contain MFA. One of these needs to match the value in the 'acr' claim of the access token." introductionVersion:"Balch"` + AuthLevelNames []string `yaml:"auth_level_name" env:"OCIS_MFA_AUTH_LEVEL_NAMES" desc:"This authentication level name indicates that multi-factor authentication was performed. The name must match the ACR claim in the access token received. Note: If multiple names are required, use a comma-separated list. The front-end service will use the first name in the list when requesting multi-factor authentication (MFA)." introductionVersion:"Balch"` } // Cache is a TTL cache configuration. diff --git a/services/proxy/pkg/middleware/mfa.go b/services/proxy/pkg/middleware/mfa.go index 389c458e1f5..f41c0b97019 100644 --- a/services/proxy/pkg/middleware/mfa.go +++ b/services/proxy/pkg/middleware/mfa.go @@ -37,6 +37,9 @@ func (m MultiFactorAuthentication) ServeHTTP(w http.ResponseWriter, req *http.Re defer m.next.ServeHTTP(w, req) if !m.enabled { + // if mfa is disabled we always set the header to true. + // this allows all other services to assume mfa is always active. + // this should reduce code and configuration complexity in other services. mfa.SetHeader(req, true) return }