From 5f188e5b6ba3b97d31bc7239be73b02879fb4825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?JJ=20=C5=81akis?= Date: Tue, 31 Dec 2024 12:46:13 +0100 Subject: [PATCH] Microsoft Entra ID provider (#2390) * Microsoft Entra ID Provider * fix typo in function name * documentation tweaks * documentation and comment tweak * docs tweaks * final tweaks * refactor: drop flag for skipping graph groups * update legacy / deprecated provider page and sort provider overview * reformat * move entra-id provider into switch (treat like every other provider * fix test case and reformat * fix sidebar configuration * apply review suggestions * add pagination for graph api * fix: do not error when groups unable to retrieve * doc: number of groups fix * restore master packages * docs: tiny docs tweak * address review comments * fix codegen --------- Co-authored-by: tuunit --- docs/docs/configuration/alpha_config.md | 11 ++ docs/docs/configuration/providers/azure_ad.md | 18 -- docs/docs/configuration/providers/gitea.md | 4 + docs/docs/configuration/providers/index.md | 27 +-- docs/docs/configuration/providers/keycloak.md | 4 +- .../providers/{azure.md => ms_azure_ad.md} | 6 +- .../configuration/providers/ms_entra_id.md | 158 +++++++++++++++ docs/sidebars.js | 32 +-- docs/src/css/custom.css | 14 ++ pkg/apis/options/legacy_options.go | 6 + pkg/apis/options/providers.go | 13 ++ providers/ms_entra_id.go | 186 ++++++++++++++++++ providers/ms_entra_id_test.go | 185 +++++++++++++++++ providers/providers.go | 4 +- 14 files changed, 617 insertions(+), 51 deletions(-) delete mode 100644 docs/docs/configuration/providers/azure_ad.md rename docs/docs/configuration/providers/{azure.md => ms_azure_ad.md} (95%) create mode 100644 docs/docs/configuration/providers/ms_entra_id.md create mode 100644 providers/ms_entra_id.go create mode 100644 providers/ms_entra_id_test.go diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index fc7c384a..55a1984b 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -385,6 +385,16 @@ character. | `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | | `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | + ### OIDCOptions (**Appears on:** [Provider](#provider)) @@ -418,6 +428,7 @@ Provider holds all configuration for a single provider | `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | | `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | | `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | | `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | | `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | | `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | diff --git a/docs/docs/configuration/providers/azure_ad.md b/docs/docs/configuration/providers/azure_ad.md deleted file mode 100644 index 8659b489..00000000 --- a/docs/docs/configuration/providers/azure_ad.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -id: azure_ad -title: Microsoft Azure AD ---- - -## Config Options - -| Flag | Toml Field | Type | Description | Default | -| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | -| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | -| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | - -## Usage - -For adding an application to the Microsoft Azure AD follow [these steps to add an application](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app). - -Take note of your `TenantId` if applicable for your situation. The `TenantId` can be used to override the default -`common` authorization server with a tenant specific server. diff --git a/docs/docs/configuration/providers/gitea.md b/docs/docs/configuration/providers/gitea.md index 5799db44..996a5ddb 100644 --- a/docs/docs/configuration/providers/gitea.md +++ b/docs/docs/configuration/providers/gitea.md @@ -3,6 +3,10 @@ id: gitea title: Gitea --- +:::note +This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + 1. Create a new application: `https://< your gitea host >/user/settings/applications` 2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` 3. Note the Client ID and Client Secret. diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index fee7b12b..9159aa33 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -8,21 +8,22 @@ with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. Valid providers are : -- [Google](google.md) _default_ -- [Azure](azure.md) - [ADFS](adfs.md) -- [Facebook](facebook.md) -- [GitHub](github.md) -- [Gitea](gitea.md) -- [Keycloak](keycloak.md)/[Keycloak OIDC](keycloak_oidc.md) -- [GitLab](gitlab.md) -- [LinkedIn](linkedin.md) -- [Microsoft Azure AD](azure_ad.md) -- [OpenID Connect](openid_connect.md) -- [login.gov](login_gov.md) -- [Nextcloud](nextcloud.md) -- [DigitalOcean](digitalocean.md) - [Bitbucket](bitbucket.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) The provider can be selected using the `provider` configuration value. diff --git a/docs/docs/configuration/providers/keycloak.md b/docs/docs/configuration/providers/keycloak.md index 1becea58..11a1abca 100644 --- a/docs/docs/configuration/providers/keycloak.md +++ b/docs/docs/configuration/providers/keycloak.md @@ -1,10 +1,10 @@ --- id: keycloak -title: Keycloak +title: Keycloak (Deprecated) --- :::note -This is the legacy provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. ::: 1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' diff --git a/docs/docs/configuration/providers/azure.md b/docs/docs/configuration/providers/ms_azure_ad.md similarity index 95% rename from docs/docs/configuration/providers/azure.md rename to docs/docs/configuration/providers/ms_azure_ad.md index 26df8e0b..4feefc68 100644 --- a/docs/docs/configuration/providers/azure.md +++ b/docs/docs/configuration/providers/ms_azure_ad.md @@ -1,8 +1,12 @@ --- id: azure -title: Azure +title: Azure (Deprecated) --- +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + ## Config Options | Flag | Toml Field | Type | Description | Default | diff --git a/docs/docs/configuration/providers/ms_entra_id.md b/docs/docs/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..082d3247 --- /dev/null +++ b/docs/docs/configuration/providers/ms_entra_id.md @@ -0,0 +1,158 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenant=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/sidebars.js b/docs/sidebars.js index 6f1b3cd5..3240e7df 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -31,22 +31,22 @@ const sidebars = { id: 'configuration/providers/index', }, items: [ - 'configuration/providers/google', - 'configuration/providers/azure', - 'configuration/providers/adfs', - 'configuration/providers/facebook', - 'configuration/providers/github', - 'configuration/providers/gitea', - 'configuration/providers/keycloak', - 'configuration/providers/keycloak_oidc', - 'configuration/providers/gitlab', - 'configuration/providers/linkedin', - 'configuration/providers/azure_ad', - 'configuration/providers/openid_connect', - 'configuration/providers/login_gov', - 'configuration/providers/nextcloud', - 'configuration/providers/digitalocean', - 'configuration/providers/bitbucket', + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect", ], }, 'configuration/session_storage', diff --git a/docs/src/css/custom.css b/docs/src/css/custom.css index 74ba0f27..fda0acd3 100644 --- a/docs/src/css/custom.css +++ b/docs/src/css/custom.css @@ -23,3 +23,17 @@ margin: 0 calc(-1 * var(--ifm-pre-padding)); padding: 0 var(--ifm-pre-padding); } + +.videoBlock { + position: relative; + padding-bottom: 75%; + height: 0; +} + +.videoBlock iframe { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index cf04afd7..ed7ae7b1 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -488,6 +488,7 @@ type LegacyProvider struct { KeycloakGroups []string `flag:"keycloak-group" cfg:"keycloak_groups"` AzureTenant string `flag:"azure-tenant" cfg:"azure_tenant"` AzureGraphGroupField string `flag:"azure-graph-group-field" cfg:"azure_graph_group_field"` + EntraIDAllowedTenants []string `flag:"entra-id-allowed-tenant" cfg:"entra_id_allowed_tenants"` BitbucketTeam string `flag:"bitbucket-team" cfg:"bitbucket_team"` BitbucketRepository string `flag:"bitbucket-repository" cfg:"bitbucket_repository"` GitHubOrg string `flag:"github-org" cfg:"github_org"` @@ -550,6 +551,7 @@ func legacyProviderFlagSet() *pflag.FlagSet { flagSet.StringSlice("keycloak-group", []string{}, "restrict logins to members of these groups (may be given multiple times)") flagSet.String("azure-tenant", "common", "go to a tenant-specific or common (tenant-independent) endpoint.") flagSet.String("azure-graph-group-field", "", "configures the group field to be used when building the groups list(`id` or `displayName`. Default is `id`) from Microsoft Graph(available only for v2.0 oidc url). Based on this value, the `allowed-group` config values should be adjusted accordingly. If using `id` as group field, `allowed-group` should contains groups IDs, if using `displayName` as group field, `allowed-group` should contains groups name") + flagSet.StringSlice("entra-id-allowed-tenant", []string{}, "list of tenants allowed for MS Entra ID multi-tenant application") flagSet.String("bitbucket-team", "", "restrict logins to members of this team") flagSet.String("bitbucket-repository", "", "restrict logins to user with access to this repository") flagSet.String("github-org", "", "restrict logins to members of this organisation") @@ -756,6 +758,10 @@ func (l *LegacyProvider) convert() (Providers, error) { UseApplicationDefaultCredentials: l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, } + case "entra-id": + provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{ + AllowedTenants: l.EntraIDAllowedTenants, + } } if l.ProviderName != "" { diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index f4e2839d..72df5633 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -30,6 +30,8 @@ type Provider struct { KeycloakConfig KeycloakOptions `json:"keycloakConfig,omitempty"` // AzureConfig holds all configurations for Azure provider. AzureConfig AzureOptions `json:"azureConfig,omitempty"` + // MicrosoftEntraIDConfig holds all configurations for Entra ID provider. + MicrosoftEntraIDConfig MicrosoftEntraIDOptions `json:"microsoftEntraIDConfig,omitempty"` // ADFSConfig holds all configurations for ADFS provider. ADFSConfig ADFSOptions `json:"ADFSConfig,omitempty"` // BitbucketConfig holds all configurations for Bitbucket provider. @@ -101,6 +103,9 @@ const ( // AzureProvider is the provider type for Azure AzureProvider ProviderType = "azure" + // MicrosoftEntraIDProvider is the provider type for Entra OIDC + MicrosoftEntraIDProvider ProviderType = "entra-id" + // BitbucketProvider is the provider type for Bitbucket BitbucketProvider ProviderType = "bitbucket" @@ -155,6 +160,14 @@ type AzureOptions struct { GraphGroupField string `json:"graphGroupField,omitempty"` } +type MicrosoftEntraIDOptions struct { + // AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are + // issued by different issuers and OIDC issuer verification needs to be disabled. + // When not specified, all tenants are allowed. Redundant for single-tenant apps + // (regular ID token validation matches the issuer). + AllowedTenants []string `json:"allowedTenants,omitempty"` +} + type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go new file mode 100644 index 00000000..74061701 --- /dev/null +++ b/providers/ms_entra_id.go @@ -0,0 +1,186 @@ +package providers + +import ( + "context" + "fmt" + "net/url" + "regexp" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" + "github.com/spf13/cast" +) + +// MicrosoftEntraIDProvider represents provider for Azure Entra Authentication V2 endpoint +type MicrosoftEntraIDProvider struct { + *OIDCProvider + multiTenantAllowedTenants []string + + microsoftGraphURL *url.URL +} + +const ( + microsoftEntraIDProviderName = "Microsoft Entra ID" +) + +var ( + microsoftGraphURL = &url.URL{ + Scheme: "https", + Host: "graph.microsoft.com", + Path: "/v1.0/me", + } +) + +// NewMicrosoftEntraIDProvider initiates a new MicrosoftEntraIDProvider +func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *MicrosoftEntraIDProvider { + p.setProviderDefaults(providerDefaults{ + name: microsoftEntraIDProviderName, + }) + + return &MicrosoftEntraIDProvider{ + OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), + + multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, + microsoftGraphURL: microsoftGraphURL, + } +} + +// EnrichSession checks for group overage after calling generic EnrichSession +func (p *MicrosoftEntraIDProvider) EnrichSession(ctx context.Context, session *sessions.SessionState) error { + if err := p.OIDCProvider.EnrichSession(ctx, session); err != nil { + return fmt.Errorf("unable to enrich session: %v", err) + } + + hasGroupOverage, err := p.checkGroupOverage(session) + if err != nil { + return fmt.Errorf("unable to check token: %v", err) + } + + if hasGroupOverage { + logger.Printf("entra overage found, reading groups from Graph API") + if err = p.addGraphGroupsToSession(ctx, session); err != nil { + return fmt.Errorf("unable to enrich session: %v", err) + } + } + + return nil +} + +// ValidateSession checks for allowed tenants (e.g. for multi-tenant apps) and passes through to generic ValidateSession +func (p *MicrosoftEntraIDProvider) ValidateSession(ctx context.Context, session *sessions.SessionState) bool { + tenant, err := p.getTenantFromToken(session) + if err != nil { + logger.Errorf("unable to retrieve entra tenant from token: %v", err) + return false + } + + if len(p.multiTenantAllowedTenants) > 0 { + tenantAllowed := p.checkTenantMatchesTenantList(tenant, p.multiTenantAllowedTenants) + if !tenantAllowed { + logger.Printf("entra: tenant %s is not specified in the list of allowed tenants", tenant) + return false + } + logger.Printf("entra: tenant %s is allowed", tenant) + } + + return p.OIDCProvider.ValidateSession(ctx, session) +} + +// checkGroupOverage checks ID token's group membership claims for the group overage +func (p *MicrosoftEntraIDProvider) checkGroupOverage(session *sessions.SessionState) (bool, error) { + extractor, err := p.getClaimExtractor(session.IDToken, session.AccessToken) + if err != nil { + return false, fmt.Errorf("unable to get claim extractor: %v", err) + } + + claimNames, _, _ := extractor.GetClaim("_claim_names") + + var claimNamesMap map[string]string + + if claimNames != nil { + claimNamesMap = cast.ToStringMapString(claimNames) + } + + if _, groupsKeyPresent := claimNamesMap["groups"]; groupsKeyPresent { + return true, nil + } + + return false, nil +} + +func (p *MicrosoftEntraIDProvider) addGraphGroupsToSession(ctx context.Context, s *sessions.SessionState) error { + groupsHeaders := makeAuthorizationHeader(tokenTypeBearer, s.AccessToken, nil) + groupsHeaders.Add("ConsistencyLevel", "eventual") + + var allGroups []string + var nextLink string + + for { + if nextLink == "" { + nextLink = fmt.Sprintf("%s/transitiveMemberOf?$select=id&$top=100", p.microsoftGraphURL) + } + + response, err := requests.New(nextLink). + WithContext(ctx). + WithHeaders(groupsHeaders). + Do(). + UnmarshalSimpleJSON() + + if err != nil { + logger.Errorf("invalid response from microsoft graph, no groups added to session: %v", err) + return nil + } + reqGroups := response.Get("value").MustArray() + + for i := range reqGroups { + value := response.Get("value").GetIndex(i).Get("id").MustString() + allGroups = append(allGroups, value) + } + + // https://learn.microsoft.com/en-us/graph/paging?view=graph-rest-1.0&tabs=http#how-paging-works + nextLink = response.Get("@odata.nextLink").MustString() + + if nextLink == "" { + break + } + } + + s.Groups = util.RemoveDuplicateStr(append(s.Groups, allGroups...)) + return nil +} + +func (p *MicrosoftEntraIDProvider) getTenantFromToken(session *sessions.SessionState) (string, error) { + extractor, err := p.getClaimExtractor(session.IDToken, session.AccessToken) + if err != nil { + return "", fmt.Errorf("unable to get claim extractor: %v", err) + } + + value, exists, err := extractor.GetClaim("iss") + + if !exists || err != nil { + return "", fmt.Errorf("iss claim does not exist in the token") + } + + pattern := `^https://login\.microsoftonline\.com/([a-zA-Z0-9-]+)/v2\.0$` + re := regexp.MustCompile(pattern) + + matches := re.FindStringSubmatch(value.(string)) + + if len(matches) > 1 { + return matches[1], nil + } + + return "", fmt.Errorf("invalid issuer in the ID token") +} + +func (p *MicrosoftEntraIDProvider) checkTenantMatchesTenantList(tenant string, allowedTenantList []string) bool { + for _, allowedTenant := range allowedTenantList { + if tenant == allowedTenant { + return true + } + } + return false +} diff --git a/providers/ms_entra_id_test.go b/providers/ms_entra_id_test.go new file mode 100644 index 00000000..b54163f0 --- /dev/null +++ b/providers/ms_entra_id_test.go @@ -0,0 +1,185 @@ +package providers + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/coreos/go-oidc/v3/oidc" + "github.com/golang-jwt/jwt/v5" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/stretchr/testify/assert" + + . "github.com/onsi/gomega" +) + +func TestAzureEntraOIDCProviderNewMultiTenant(t *testing.T) { + g := NewWithT(t) + + provider := NewMicrosoftEntraIDProvider(&ProviderData{}, + options.Provider{OIDCConfig: options.OIDCOptions{ + IssuerURL: "https://login.microsoftonline.com/common/v2.0", + InsecureSkipIssuerVerification: true, + }}, + ) + g.Expect(provider.Data().ProviderName).To(Equal("Microsoft Entra ID")) +} + +func TestAzureEntraOIDCProviderNewSingleTenant(t *testing.T) { + g := NewWithT(t) + + provider := NewMicrosoftEntraIDProvider(&ProviderData{}, + options.Provider{OIDCConfig: options.OIDCOptions{ + IssuerURL: "https://login.microsoftonline.com/18014347-dd57-41a1-8191-7a1f734ea457/v2.0", + }}, + ) + g.Expect(provider.Data().ProviderName).To(Equal("Microsoft Entra ID")) +} + +func TestAzureEntraOIDCProviderEnrichSessionGroupOverage(t *testing.T) { + // Create ID Token that indicates group overage with _claim_names + key, _ := rsa.GenerateKey(rand.Reader, 2048) + claimsWithGroupOverage := &claimsWithGroupOverage{ + jwt.RegisteredClaims{ + Issuer: "https://login.microsoftonline.com/18014347-dd57-41a1-8191-7a1f734ea457/v2.0", + }, + map[string]string{"groups": "src1"}, + } + + jwtWithClaims := jwt.NewWithClaims(jwt.SigningMethodRS256, claimsWithGroupOverage) + signedJWT, err := jwtWithClaims.SignedString(key) + + assert.NoError(t, err) + + session := CreateAuthorizedSession() + session.IDToken = signedJWT + session.Email = "mock@example.com" + + // Create provider + provider := NewMicrosoftEntraIDProvider(&ProviderData{}, + options.Provider{OIDCConfig: options.OIDCOptions{ + IssuerURL: "https://login.microsoftonline.com/18014347-dd57-41a1-8191-7a1f734ea457/v2.0", + }}, + ) + + // Create mocked Azure Graph server and override Graph URL + mockedGraph := mockGraphAPI(false) + mockedGraphURL, _ := url.Parse(mockedGraph.URL) + updateURL(provider.microsoftGraphURL, mockedGraphURL.Host) + + // Test EnrichSession + err = provider.EnrichSession(context.Background(), session) + + assert.NoError(t, err) + assert.Contains(t, session.Groups, "85d7d600-7804-4d92-8d43-9c33c21c130c") + assert.Contains(t, session.Groups, "916f0604-8a3b-4a69-bda9-06db11a8f0cd") + assert.Contains(t, session.Groups, "b1aef995-6b55-4ac6-bbfe-e829810e9352", "Pagination using $skiptoken failed") +} + +func TestAzureEntraOIDCProviderValidateSessionAllowedTenants(t *testing.T) { + // Create multi-tenant Azure Entra provider with allowed tenants + provider := NewMicrosoftEntraIDProvider( + &ProviderData{ + Verifier: &mockedVerifier{}, + }, + options.Provider{ + OIDCConfig: options.OIDCOptions{ + IssuerURL: "https://login.microsoftonline.com/common/v2.0", + InsecureSkipIssuerVerification: true, + InsecureSkipNonce: true, + }, + MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ + AllowedTenants: []string{"85d7d600-7804-4d92-8d43-9c33c21c130c"}, + }, + }, + ) + + // Check for invalid tenant + key, _ := rsa.GenerateKey(rand.Reader, 2048) + + idToken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.RegisteredClaims{ + Issuer: "https://login.microsoftonline.com/invalid_tenant/v2.0", + }) + invalidJWT, err := idToken.SignedString(key) + assert.NoError(t, err) + + session := CreateAuthorizedSession() + session.IDToken = invalidJWT + + valid := provider.ValidateSession(context.Background(), session) + assert.False(t, valid) + + // Check for valid tenant + idToken = jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.RegisteredClaims{ + Issuer: "https://login.microsoftonline.com/85d7d600-7804-4d92-8d43-9c33c21c130c/v2.0", + }) + validJWT, err := idToken.SignedString(key) + assert.NoError(t, err) + + session = CreateAuthorizedSession() + session.IDToken = validJWT + + valid = provider.ValidateSession(context.Background(), session) + assert.True(t, valid) +} + +func mockGraphAPI(noGroupMemberPermissions bool) *httptest.Server { + groupsPath := "/v1.0/me/transitiveMemberOf" + + return httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + if noGroupMemberPermissions { + w.WriteHeader(401) + } else if r.URL.Path == groupsPath && r.Method == http.MethodGet && len(r.URL.Query()["$skiptoken"]) > 0 { + // Second page (pagination) + w.Write([]byte(`{ + "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects(id)", + "value": [ + { + "@odata.type": "#microsoft.graph.group", + "id": "b1aef995-6b55-4ac6-bbfe-e829810e9352" + } + ] + }`)) + + } else if r.URL.Path == groupsPath && r.Method == http.MethodGet { + // First page (pagination) + w.Write([]byte(fmt.Sprintf(`{ + "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects(id)", + "@odata.nextLink": "http://%s/v1.0/me/transitiveMemberOf?$select=id&$top=2&$skiptoken=TEST_TOKEN", + "value": [ + { + "@odata.type": "#microsoft.graph.group", + "id": "85d7d600-7804-4d92-8d43-9c33c21c130c" + }, + { + "@odata.type": "#microsoft.graph.group", + "id": "916f0604-8a3b-4a69-bda9-06db11a8f0cd" + } + ] + }`, r.Host))) + } + }, + )) +} + +type claimsWithGroupOverage struct { + jwt.RegisteredClaims + ClaimNames interface{} `json:"_claim_names,omitempty"` +} + +func (c *claimsWithGroupOverage) Valid() error { + return nil +} + +type mockedVerifier struct { +} + +func (v *mockedVerifier) Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error) { + return nil, nil +} diff --git a/providers/providers.go b/providers/providers.go index 503b3559..72204e55 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -41,6 +41,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) { return NewADFSProvider(providerData, providerConfig), nil case options.AzureProvider: return NewAzureProvider(providerData, providerConfig.AzureConfig), nil + case options.MicrosoftEntraIDProvider: + return NewMicrosoftEntraIDProvider(providerData, providerConfig), nil case options.BitbucketProvider: return NewBitbucketProvider(providerData, providerConfig.BitbucketConfig), nil case options.DigitalOceanProvider: @@ -181,7 +183,7 @@ func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bo case options.BitbucketProvider, options.DigitalOceanProvider, options.FacebookProvider, options.GitHubProvider, options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider: return false, nil - case options.ADFSProvider, options.AzureProvider, options.GitLabProvider, options.KeycloakOIDCProvider, options.OIDCProvider: + case options.ADFSProvider, options.AzureProvider, options.GitLabProvider, options.KeycloakOIDCProvider, options.OIDCProvider, options.MicrosoftEntraIDProvider: return true, nil default: return false, fmt.Errorf("unknown provider type: %s", providerType)