feat: document mfa package
Signed-off-by: Julian Koberg <julian.koberg@kiteworks.com>
This commit is contained in:
1 parent
824a71dbe2
commit
dda6104722
13 files changed
+122
-32
No files matched your search
+25
-19
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user