public void Configure( IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, GlobalSettings globalSettings, ILogger <Startup> logger) { IdentityModelEventSource.ShowPII = true; app.UseSerilog(env, appLifetime, globalSettings); // Default Middleware app.UseDefaultMiddleware(env, globalSettings); if (!globalSettings.SelfHosted) { // Rate limiting app.UseMiddleware <CustomIpRateLimitMiddleware>(); } else { app.UseForwardedHeaders(globalSettings); } // Add localization app.UseCoreLocalization(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add routing app.UseRouting(); // Add Cors app.UseCors(policy => policy.SetIsOriginAllowed(o => CoreHelpers.IsCorsOriginAllowed(o, globalSettings)) .AllowAnyMethod().AllowAnyHeader().AllowCredentials()); // Add authentication and authorization to the request pipeline. app.UseAuthentication(); app.UseAuthorization(); // Add current context app.UseMiddleware <CurrentContextMiddleware>(); // Add endpoints to the request pipeline. app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); // Add Swagger if (Environment.IsDevelopment() || globalSettings.SelfHosted) { app.UseSwagger(config => { config.RouteTemplate = "specs/{documentName}/swagger.json"; config.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Servers = new List <OpenApiServer> { new OpenApiServer { Url = globalSettings.BaseServiceUri.Api } }); }); app.UseSwaggerUI(config => { config.DocumentTitle = "Bitwarden API Documentation"; config.RoutePrefix = "docs"; config.SwaggerEndpoint($"{globalSettings.BaseServiceUri.Api}/specs/public/swagger.json", "Bitwarden Public API"); config.OAuthClientId("accountType.id"); config.OAuthClientSecret("secretKey"); }); } //app.Map("/connect", _app => _app.RunProxy(new ProxyOptions() { Host = "localhost", Port = "33656", Scheme = "http" })); if (Environment.IsDevelopment()) { app.RunProxy(new ProxyOptions() { Host = "localhost", Port = "8080", Scheme = "http" }); } else { // fix for routing clientapp : base/bitwarden => base/bitwarden/ app.MapWhen(context => !context.Request.Path.HasValue, _app => _app.Run(async context => { context.Response.Redirect(context.Request.PathBase + "/"); await Task.CompletedTask; })); app.UseSpaStaticFiles(); app.UseSpa(spa => { spa.Options.SourcePath = "clientapp"; }); } // Log startup logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started."); }
// Hide the default constructor private TaskbarManager() { CoreHelpers.ThrowIfNotWin7(); }
public void ConfigureServices(IServiceCollection services) { var provider = services.BuildServiceProvider(); // Options services.AddOptions(); // Settings var globalSettings = services.AddGlobalSettingsServices(Configuration); if (!globalSettings.SelfHosted) { services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimitOptions")); services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies")); } // Data Protection services.AddCustomDataProtectionServices(Environment, globalSettings); // Stripe Billing StripeConfiguration.ApiKey = globalSettings.StripeApiKey; // Repositories services.AddSqlServerRepositories(globalSettings); // Context services.AddScoped <CurrentContext>(); // Caching services.AddMemoryCache(); // BitPay services.AddSingleton <BitPayClient>(); if (!globalSettings.SelfHosted) { // Rate limiting services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); } // Identity services.AddCustomIdentityServices(globalSettings); services.AddIdentityAuthenticationServices(globalSettings, Environment, config => { config.AddPolicy("Application", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application"); policy.RequireClaim(JwtClaimTypes.Scope, "api"); }); config.AddPolicy("Web", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application"); policy.RequireClaim(JwtClaimTypes.Scope, "api"); policy.RequireClaim(JwtClaimTypes.ClientId, "web"); }); config.AddPolicy("Push", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.Scope, "api.push"); }); config.AddPolicy("Licensing", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.Scope, "api.licensing"); }); config.AddPolicy("Organization", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.Scope, "api.organization"); }); }); services.AddScoped <AuthenticatorTokenProvider>(); // Services services.AddBaseServices(); services.AddDefaultServices(globalSettings); // MVC services.AddMvc(config => { config.Conventions.Add(new ApiExplorerGroupConvention()); config.Conventions.Add(new PublicApiControllersModelConvention()); }).AddJsonOptions(options => { if (Environment.IsProduction() && Configuration["swaggerGen"] != "true") { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); } }); services.AddSwagger(globalSettings); if (globalSettings.SelfHosted) { // Jobs service Jobs.JobsHostedService.AddJobsServices(services); services.AddHostedService <Jobs.JobsHostedService>(); } if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName)) { services.AddHostedService <Core.HostedServices.ApplicationCacheHostedService>(); } }
public void SetNewId() { Id = CoreHelpers.GenerateComb(); }
public async Task <Tuple <bool, string> > SignUpPremiumAsync(User user, string paymentToken, PaymentMethodType paymentMethodType, short additionalStorageGb, UserLicense license, TaxInfo taxInfo) { if (user.Premium) { throw new BadRequestException("Already a premium user."); } if (additionalStorageGb < 0) { throw new BadRequestException("You can't subtract storage!"); } if ((paymentMethodType == PaymentMethodType.GoogleInApp || paymentMethodType == PaymentMethodType.AppleInApp) && additionalStorageGb > 0) { throw new BadRequestException("You cannot add storage with this payment method."); } string paymentIntentClientSecret = null; IPaymentService paymentService = null; if (_globalSettings.SelfHosted) { if (license == null || !_licenseService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } if (!license.CanUse(user)) { throw new BadRequestException("This license is not valid for this user."); } var dir = $"{_globalSettings.LicenseDirectory}/user"; Directory.CreateDirectory(dir); File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented)); } else { paymentIntentClientSecret = await _paymentService.PurchasePremiumAsync(user, paymentMethodType, paymentToken, additionalStorageGb, taxInfo); } user.Premium = true; user.RevisionDate = DateTime.UtcNow; if (_globalSettings.SelfHosted) { user.MaxStorageGb = 10240; // 10 TB user.LicenseKey = license.LicenseKey; user.PremiumExpirationDate = license.Expires; } else { user.MaxStorageGb = (short)(1 + additionalStorageGb); user.LicenseKey = CoreHelpers.SecureRandomString(20); } try { await SaveUserAsync(user); await _pushService.PushSyncVaultAsync(user.Id); await _referenceEventService.RaiseEventAsync( new ReferenceEvent(ReferenceEventType.UpgradePlan, user) { Storage = user.MaxStorageGb, PlanName = PremiumPlanId, }); } catch when(!_globalSettings.SelfHosted) { await paymentService.CancelAndRecoverChargesAsync(user); throw; } return(new Tuple <bool, string>(string.IsNullOrWhiteSpace(paymentIntentClientSecret), paymentIntentClientSecret)); }
// Let Windows handle the rendering. /// <summary> /// Creates a new instance of this class. /// </summary> public CommandLink() { CoreHelpers.ThrowIfNotVista(); FlatStyle = FlatStyle.System; }
[Obsolete] // because parent is obsolete public override bool ShouldOverrideUrlLoading(WebView view, string url) { Uri uri = new Uri(url); if (url.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase)) { // TODO(migration): Figure out how to get logger into this class. MsalLogger.Default.Verbose("It is browser launch request"); OpenLinkInBrowser(url, Activity); view.StopLoading(); Activity.Finish(); return(true); } if (url.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase)) { // TODO(migration): Figure out how to get logger into this class. MsalLogger.Default.Verbose("It is an azure authenticator install request"); view.StopLoading(); Finish(Activity, url); return(true); } if (url.StartsWith(BrokerConstants.ClientTlsRedirect, StringComparison.OrdinalIgnoreCase)) { string query = uri.Query; if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } Dictionary <string, string> keyPair = CoreHelpers.ParseKeyValueList(query, '&', true, false, null); string responseHeader = DeviceAuthHelper.CreateDeviceAuthChallengeResponseAsync(keyPair).Result; Dictionary <string, string> pkeyAuthEmptyResponse = new Dictionary <string, string> { [BrokerConstants.ChallangeResponseHeader] = responseHeader }; view.LoadUrl(keyPair["SubmitUrl"], pkeyAuthEmptyResponse); return(true); } if (url.StartsWith(_callback, StringComparison.OrdinalIgnoreCase)) { Finish(Activity, url); return(true); } if (!url.Equals(AboutBlankUri, StringComparison.OrdinalIgnoreCase) && !uri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { UriBuilder errorUri = new UriBuilder(_callback) { Query = string.Format( CultureInfo.InvariantCulture, "error={0}&error_description={1}", MsalError.NonHttpsRedirectNotSupported, MsalErrorMessage.NonHttpsRedirectNotSupported) }; Finish(Activity, errorUri.ToString()); return(true); } return(false); }
private async Task <Dictionary <string, object> > BuildTwoFactorParams(Organization organization, User user, TwoFactorProviderType type, TwoFactorProvider provider) { switch (type) { case TwoFactorProviderType.Duo: case TwoFactorProviderType.U2f: case TwoFactorProviderType.WebAuthn: case TwoFactorProviderType.Email: case TwoFactorProviderType.YubiKey: if (!(await _userService.TwoFactorProviderIsEnabledAsync(type, user))) { return(null); } var token = await _userManager.GenerateTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(type)); if (type == TwoFactorProviderType.Duo) { return(new Dictionary <string, object> { ["Host"] = provider.MetaData["Host"], ["Signature"] = token }); } else if (type == TwoFactorProviderType.U2f) { // TODO: Remove "Challenges" in a future update. Deprecated. var tokens = token?.Split('|'); return(new Dictionary <string, object> { ["Challenge"] = tokens != null && tokens.Length > 0 ? tokens[0] : null, ["Challenges"] = tokens != null && tokens.Length > 1 ? tokens[1] : null }); } else if (type == TwoFactorProviderType.WebAuthn) { return(JsonSerializer.Deserialize <Dictionary <string, object> >(token)); } else if (type == TwoFactorProviderType.Email) { return(new Dictionary <string, object> { ["Email"] = token }); } else if (type == TwoFactorProviderType.YubiKey) { return(new Dictionary <string, object> { ["Nfc"] = (bool)provider.MetaData["Nfc"] }); } return(null); case TwoFactorProviderType.OrganizationDuo: if (await _organizationDuoWebTokenProvider.CanGenerateTwoFactorTokenAsync(organization)) { return(new Dictionary <string, object> { ["Host"] = provider.MetaData["Host"], ["Signature"] = await _organizationDuoWebTokenProvider.GenerateAsync(organization, user) }); } return(null); default: return(null); } }
private Dictionary <string, string> CreateAuthorizationRequestParameters(Uri redirectUriOverride = null) { var extraScopesToConsent = new HashSet <string>(StringComparer.OrdinalIgnoreCase); if (!_interactiveParameters.ExtraScopesToConsent.IsNullOrEmpty()) { extraScopesToConsent = ScopeHelper.CreateScopeSet(_interactiveParameters.ExtraScopesToConsent); } if (extraScopesToConsent.Contains(_requestParams.AppConfig.ClientId)) { throw new ArgumentException("API does not accept client id as a user-provided scope"); } var unionScope = ScopeHelper.GetMsalScopes( new HashSet <string>(_requestParams.Scope.Concat(extraScopesToConsent))); var authorizationRequestParameters = new Dictionary <string, string> { [OAuth2Parameter.Scope] = unionScope.AsSingleString(), [OAuth2Parameter.ResponseType] = OAuth2ResponseType.Code, [OAuth2Parameter.ClientId] = _requestParams.AppConfig.ClientId, [OAuth2Parameter.RedirectUri] = redirectUriOverride?.OriginalString ?? _requestParams.RedirectUri.OriginalString }; if (!string.IsNullOrWhiteSpace(_requestParams.ClaimsAndClientCapabilities)) { authorizationRequestParameters[OAuth2Parameter.Claims] = _requestParams.ClaimsAndClientCapabilities; } //CcsRoutingHint passed in from WithCcsRoutingHint() will override the AAD backup authentication system Hint created from the login hint if (!string.IsNullOrWhiteSpace(_interactiveParameters.LoginHint) || _requestParams.CcsRoutingHint != null) { string OidCcsHeader; if (_requestParams.CcsRoutingHint == null) { authorizationRequestParameters[OAuth2Parameter.LoginHint] = _interactiveParameters.LoginHint; OidCcsHeader = CoreHelpers.GetCcsUpnHint(_interactiveParameters.LoginHint); } else { authorizationRequestParameters[OAuth2Parameter.LoginHint] = _interactiveParameters.LoginHint; OidCcsHeader = CoreHelpers.GetCcsClientInfoHint(_requestParams.CcsRoutingHint.Value.Key, _requestParams.CcsRoutingHint.Value.Value); } //The AAD backup authentication system header is used by the AAD backup authentication system service //to help route requests to resources in Azure during requests to speed up authentication. //It consists of either the ObjectId.TenantId or the upn of the account signign in. //See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2525 authorizationRequestParameters[Constants.CcsRoutingHintHeader] = OidCcsHeader; } if (_requestParams.RequestContext.CorrelationId != Guid.Empty) { authorizationRequestParameters[OAuth2Parameter.CorrelationId] = _requestParams.RequestContext.CorrelationId.ToString(); } foreach (KeyValuePair <string, string> kvp in MsalIdHelper.GetMsalIdParameters(_requestParams.RequestContext.Logger)) { authorizationRequestParameters[kvp.Key] = kvp.Value; } if (_interactiveParameters.Prompt == Prompt.NotSpecified) { authorizationRequestParameters[OAuth2Parameter.Prompt] = Prompt.SelectAccount.PromptValue; } else if (_interactiveParameters.Prompt.PromptValue != Prompt.NoPrompt.PromptValue) { authorizationRequestParameters[OAuth2Parameter.Prompt] = _interactiveParameters.Prompt.PromptValue; } return(authorizationRequestParameters); }
public ShellSavedSearchCollection(IShellItem2 shellItem) : base(shellItem) { CoreHelpers.ThrowIfNotVista(); }
public MsalTokenResponse ParseSuccessfullWamResponse( WebTokenResponse webTokenResponse, out Dictionary <string, string> allProperties) { allProperties = new Dictionary <string, string>(8, StringComparer.OrdinalIgnoreCase); if (!webTokenResponse.Properties.TryGetValue("TokenExpiresOn", out string expiresOn)) { _logger.Warning("Result from WAM does not have expiration. Marking access token as expired."); expiresOn = null; } if (!webTokenResponse.Properties.TryGetValue("ExtendedLifetimeToken", out string extendedExpiresOn)) { extendedExpiresOn = null; } if (!webTokenResponse.Properties.TryGetValue("Authority", out string authority)) { _logger.Error("Result from WAM does not have authority."); return(new MsalTokenResponse() { Error = "no_authority_in_wam_response", ErrorDescription = "No authority in WAM response" }); } if (!webTokenResponse.Properties.TryGetValue("correlationId", out string correlationId)) { _logger.Warning("No correlation ID in response"); correlationId = null; } bool hasIdToken = webTokenResponse.Properties.TryGetValue("wamcompat_id_token", out string idToken); _logger.Info("Result from WAM has id token? " + hasIdToken); bool hasClientInfo = webTokenResponse.Properties.TryGetValue("wamcompat_client_info", out string clientInfo); _logger.Info("Result from WAM has client info? " + hasClientInfo); bool hasScopes = webTokenResponse.Properties.TryGetValue("wamcompat_scopes", out string scopes); _logger.InfoPii("Result from WAM scopes: " + scopes, "Result from WAM has scopes? " + hasScopes); foreach (var kvp in webTokenResponse.Properties) { allProperties[kvp.Key] = kvp.Value; } MsalTokenResponse msalTokenResponse = new MsalTokenResponse() { AccessToken = webTokenResponse.Token, IdToken = idToken, CorrelationId = correlationId, Scope = scopes, ExpiresIn = CoreHelpers.GetDurationFromWindowsTimestamp(expiresOn, _logger), ExtendedExpiresIn = CoreHelpers.GetDurationFromWindowsTimestamp(extendedExpiresOn, _logger), ClientInfo = clientInfo, TokenType = "Bearer", WamAccountId = webTokenResponse?.WebAccount?.Id, TokenSource = TokenSource.Broker }; return(msalTokenResponse); }
public void ConfigureServices(IServiceCollection services) { // Options services.AddOptions(); // Settings var globalSettings = services.AddGlobalSettingsServices(Configuration, Environment); if (!globalSettings.SelfHosted) { services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimitOptions")); services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies")); } // Data Protection services.AddCustomDataProtectionServices(Environment, globalSettings); // Event Grid if (!string.IsNullOrWhiteSpace(globalSettings.EventGridKey)) { ApiHelpers.EventGridKey = globalSettings.EventGridKey; } // Stripe Billing StripeConfiguration.ApiKey = globalSettings.Stripe.ApiKey; StripeConfiguration.MaxNetworkRetries = globalSettings.Stripe.MaxNetworkRetries; // Repositories services.AddSqlServerRepositories(globalSettings); // Context services.AddScoped <ICurrentContext, CurrentContext>(); // Caching services.AddMemoryCache(); // BitPay services.AddSingleton <BitPayClient>(); if (!globalSettings.SelfHosted) { // Rate limiting services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); } // Identity services.AddCustomIdentityServices(globalSettings); services.AddIdentityAuthenticationServices(globalSettings, Environment, config => { config.AddPolicy("Application", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application", "external"); policy.RequireClaim(JwtClaimTypes.Scope, "api"); }); config.AddPolicy("Web", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application", "external"); policy.RequireClaim(JwtClaimTypes.Scope, "api"); policy.RequireClaim(JwtClaimTypes.ClientId, "web"); }); config.AddPolicy("Push", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.Scope, "api.push"); }); config.AddPolicy("Licensing", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.Scope, "api.licensing"); }); config.AddPolicy("Organization", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(JwtClaimTypes.Scope, "api.organization"); }); }); services.AddScoped <AuthenticatorTokenProvider>(); // Services services.AddBaseServices(); services.AddDefaultServices(globalSettings); services.AddCoreLocalizationServices(); #if OSS services.AddOosServices(); #else services.AddCommCoreServices(); #endif // MVC services.AddMvc(config => { config.Conventions.Add(new ApiExplorerGroupConvention()); config.Conventions.Add(new PublicApiControllersModelConvention()); }); services.AddSwagger(globalSettings); Jobs.JobsHostedService.AddJobsServices(services); services.AddHostedService <Jobs.JobsHostedService>(); if (globalSettings.SelfHosted) { // Jobs service Jobs.JobsHostedService.AddJobsServices(services); services.AddHostedService <Jobs.JobsHostedService>(); } if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName)) { services.AddHostedService <Core.HostedServices.ApplicationCacheHostedService>(); } }
public void Configure( IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, GlobalSettings globalSettings, ILogger <Startup> logger) { IdentityModelEventSource.ShowPII = true; app.UseSerilog(env, appLifetime, globalSettings); // Add general security headers app.UseMiddleware <SecurityHeadersMiddleware>(); // Default Middleware app.UseDefaultMiddleware(env, globalSettings); if (!globalSettings.SelfHosted) { // Rate limiting app.UseMiddleware <CustomIpRateLimitMiddleware>(); } else { app.UseForwardedHeaders(globalSettings); } // Add localization app.UseCoreLocalization(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add routing app.UseRouting(); // Add Cors app.UseCors(policy => policy.SetIsOriginAllowed(o => CoreHelpers.IsCorsOriginAllowed(o, globalSettings)) .AllowAnyMethod().AllowAnyHeader().AllowCredentials()); // Add authentication and authorization to the request pipeline. app.UseAuthentication(); app.UseAuthorization(); // Add current context app.UseMiddleware <CurrentContextMiddleware>(); // Add endpoints to the request pipeline. app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); // Add Swagger if (Environment.IsDevelopment() || globalSettings.SelfHosted) { app.UseSwagger(config => { config.RouteTemplate = "specs/{documentName}/swagger.json"; config.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Servers = new List <OpenApiServer> { new OpenApiServer { Url = globalSettings.BaseServiceUri.Api } }); }); app.UseSwaggerUI(config => { config.DocumentTitle = "Bitwarden API Documentation"; config.RoutePrefix = "docs"; config.SwaggerEndpoint($"{globalSettings.BaseServiceUri.Api}/specs/public/swagger.json", "Bitwarden Public API"); config.OAuthClientId("accountType.id"); config.OAuthClientSecret("secretKey"); }); } // Log startup logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started."); }
public void Configure( IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, GlobalSettings globalSettings, ILogger <Startup> logger) { if (env.IsDevelopment() || globalSettings.SelfHosted) { IdentityModelEventSource.ShowPII = true; } app.UseSerilog(env, appLifetime, globalSettings); if (!env.IsDevelopment()) { var uri = new Uri(globalSettings.BaseServiceUri.Sso); app.Use(async(ctx, next) => { ctx.SetIdentityServerOrigin($"{uri.Scheme}://{uri.Host}"); await next(); }); } if (globalSettings.SelfHosted) { app.UsePathBase("/sso"); app.UseForwardedHeaders(globalSettings); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseCookiePolicy(); } else { app.UseExceptionHandler("/Error"); } app.UseCoreLocalization(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add routing app.UseRouting(); // Add Cors app.UseCors(policy => policy.SetIsOriginAllowed(o => CoreHelpers.IsCorsOriginAllowed(o, globalSettings)) .AllowAnyMethod().AllowAnyHeader().AllowCredentials()); // Add current context app.UseMiddleware <CurrentContextMiddleware>(); // Add IdentityServer to the request pipeline. app.UseIdentityServer(new IdentityServerMiddlewareOptions { AuthenticationMiddleware = app => app.UseMiddleware <SsoAuthenticationMiddleware>() }); // Add Mvc stuff app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); // Log startup logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started."); }
public void GenerateComb_WithInputs_Success(Guid inputGuid, DateTime inputTime, Guid expectedComb) { var comb = CoreHelpers.GenerateComb(inputGuid, inputTime); Assert.Equal(expectedComb, comb); }
public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action <WKNavigationActionPolicy> decisionHandler) { string requestUrlString = navigationAction.Request.Url.ToString(); // If the URL has the browser:// scheme then this is a request to open an external browser if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase)) { DispatchQueue.MainQueue.DispatchAsync(() => AuthenticationAgentUIViewController.CancelAuthentication(null, null)); // Build the HTTPS URL for launching with an external browser var httpsUrlBuilder = new UriBuilder(requestUrlString) { Scheme = Uri.UriSchemeHttps }; requestUrlString = httpsUrlBuilder.Uri.AbsoluteUri; DispatchQueue.MainQueue.DispatchAsync( () => UIApplication.SharedApplication.OpenUrl(new NSUrl(requestUrlString))); AuthenticationAgentUIViewController.DismissViewController(true, null); decisionHandler(WKNavigationActionPolicy.Cancel); return; } if (requestUrlString.StartsWith(AuthenticationAgentUIViewController.callback, StringComparison.OrdinalIgnoreCase) || requestUrlString.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase)) { AuthenticationAgentUIViewController.DismissViewController(true, () => AuthenticationAgentUIViewController.callbackMethod(new AuthorizationResult(AuthorizationStatus.Success, requestUrlString))); decisionHandler(WKNavigationActionPolicy.Cancel); return; } if (requestUrlString.StartsWith(BrokerConstants.DeviceAuthChallengeRedirect, StringComparison.OrdinalIgnoreCase)) { Uri uri = new Uri(requestUrlString); string query = uri.Query; if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } Dictionary <string, string> keyPair = CoreHelpers.ParseKeyValueList(query, '&', true, false, null); string responseHeader = DeviceAuthHelper.CreateDeviceAuthChallengeResponseAsync(keyPair).Result; NSMutableUrlRequest newRequest = (NSMutableUrlRequest)navigationAction.Request.MutableCopy(); newRequest.Url = new NSUrl(keyPair["SubmitUrl"]); newRequest[BrokerConstants.ChallengeResponseHeader] = responseHeader; webView.LoadRequest(newRequest); decisionHandler(WKNavigationActionPolicy.Cancel); return; } if (!navigationAction.Request.Url.AbsoluteString.Equals(AboutBlankUri, StringComparison.OrdinalIgnoreCase) && !navigationAction.Request.Url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.ErrorHttp) { Error = CoreErrorCodes.NonHttpsRedirectNotSupported, ErrorDescription = CoreErrorMessages.NonHttpsRedirectNotSupported }; AuthenticationAgentUIViewController.DismissViewController(true, () => AuthenticationAgentUIViewController.callbackMethod(result)); decisionHandler(WKNavigationActionPolicy.Cancel); return; } decisionHandler(WKNavigationActionPolicy.Allow); return; }
public void Configure( IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, GlobalSettings globalSettings) { IdentityModelEventSource.ShowPII = true; app.UseSerilog(env, appLifetime, globalSettings); // Add general security headers app.UseMiddleware <SecurityHeadersMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/alive", async context => await context.Response.WriteAsJsonAsync(System.DateTime.UtcNow)); endpoints.MapGet("/now", async context => await context.Response.WriteAsJsonAsync(System.DateTime.UtcNow)); endpoints.MapGet("/version", async context => await context.Response.WriteAsJsonAsync(CoreHelpers.GetVersion())); }); }
public void ToEpocMilliseconds_Success(DateTime date, long milliseconds) { // Act & Assert Assert.Equal(milliseconds, CoreHelpers.ToEpocMilliseconds(date)); }
public void ConfigureServices(IServiceCollection services) { // Options services.AddOptions(); // Settings var globalSettings = services.AddGlobalSettingsServices(Configuration, Environment); services.Configure <AdminSettings>(Configuration.GetSection("AdminSettings")); // Data Protection services.AddCustomDataProtectionServices(Environment, globalSettings); // Stripe Billing StripeConfiguration.ApiKey = globalSettings.Stripe.ApiKey; StripeConfiguration.MaxNetworkRetries = globalSettings.Stripe.MaxNetworkRetries; // Repositories services.AddSqlServerRepositories(globalSettings); // Context services.AddScoped <ICurrentContext, CurrentContext>(); // Identity services.AddPasswordlessIdentityServices <ReadOnlyEnvIdentityUserStore>(globalSettings); services.Configure <SecurityStampValidatorOptions>(options => { options.ValidationInterval = TimeSpan.FromMinutes(5); }); if (globalSettings.SelfHosted) { services.ConfigureApplicationCookie(options => { options.Cookie.Path = "/admin"; }); } // Services services.AddBaseServices(globalSettings); services.AddDefaultServices(globalSettings); #if OSS services.AddOosServices(); #else services.AddCommCoreServices(); #endif // Mvc services.AddMvc(config => { config.Filters.Add(new LoggingExceptionHandlerFilterAttribute()); }); services.Configure <RouteOptions>(options => options.LowercaseUrls = true); // Jobs service Jobs.JobsHostedService.AddJobsServices(services, globalSettings.SelfHosted); services.AddHostedService <Jobs.JobsHostedService>(); if (globalSettings.SelfHosted) { services.AddHostedService <HostedServices.DatabaseMigrationHostedService>(); } else { if (CoreHelpers.SettingHasValue(globalSettings.Storage.ConnectionString)) { services.AddHostedService <HostedServices.AzureQueueBlockIpHostedService>(); } else if (CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) { services.AddHostedService <HostedServices.AmazonSqsBlockIpHostedService>(); } if (CoreHelpers.SettingHasValue(globalSettings.Mail.ConnectionString)) { services.AddHostedService <HostedServices.AzureQueueMailHostedService>(); } } }
public void FromEpocMilliseconds(DateTime date, long milliseconds) { // Act & Assert Assert.Equal(date, CoreHelpers.FromEpocMilliseconds(milliseconds)); }
public async Task SignUpPremiumAsync(User user, string paymentToken, short additionalStorageGb, UserLicense license) { if (user.Premium) { throw new BadRequestException("Already a premium user."); } IPaymentService paymentService = null; if (_globalSettings.SelfHosted) { if (license == null || !_licenseService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } if (!license.CanUse(user)) { throw new BadRequestException("This license is not valid for this user."); } var dir = $"{_globalSettings.LicenseDirectory}/user"; Directory.CreateDirectory(dir); File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented)); } else if (!string.IsNullOrWhiteSpace(paymentToken)) { if (paymentToken.StartsWith("btok_")) { throw new BadRequestException("Invalid token."); } if (paymentToken.StartsWith("tok_")) { paymentService = new StripePaymentService(); } else { paymentService = new BraintreePaymentService(_globalSettings); } await paymentService.PurchasePremiumAsync(user, paymentToken, additionalStorageGb); } else { throw new InvalidOperationException("License or payment token is required."); } user.Premium = true; user.RevisionDate = DateTime.UtcNow; if (_globalSettings.SelfHosted) { user.MaxStorageGb = 10240; // 10 TB user.LicenseKey = license.LicenseKey; user.PremiumExpirationDate = license.Expires; } else { user.MaxStorageGb = (short)(1 + additionalStorageGb); user.LicenseKey = CoreHelpers.SecureRandomString(20); } try { await SaveUserAsync(user); } catch when(!_globalSettings.SelfHosted) { await paymentService.CancelAndRecoverChargesAsync(user); throw; } }
public void ReadableBytesSize_Success(long size, string readable) { // Act & Assert Assert.Equal(readable, CoreHelpers.ReadableBytesSize(size)); }
public async Task RotateApiKeyAsync(User user) { user.ApiKey = CoreHelpers.SecureRandomString(30); user.RevisionDate = DateTime.UtcNow; await _userRepository.ReplaceAsync(user); }
public void PunyEncode_Success(string text, string expected) { var actual = CoreHelpers.PunyEncode(text); Assert.Equal(expected, actual); }
void DecidePolicyForNavigation(WebView webView, NSDictionary actionInformation, NSUrlRequest request, WebFrame frame, NSObject decisionToken) { if (request == null) { WebView.DecideUse(decisionToken); return; } string requestUrlString = request.Url.ToString(); if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase)) { var result = AuthorizationResult.FromStatus( AuthorizationStatus.ProtocolError, "Unsupported request", "Server is redirecting client to browser. This behavior is not yet defined on Mac OS X."); _callbackMethod(result); WebView.DecideIgnore(decisionToken); Close(); return; } if (requestUrlString.ToLower(CultureInfo.InvariantCulture).StartsWith(_callback.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) || requestUrlString.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase)) { _callbackMethod(AuthorizationResult.FromUri(request.Url.ToString())); WebView.DecideIgnore(decisionToken); Close(); return; } if (requestUrlString.StartsWith(BrokerConstants.DeviceAuthChallengeRedirect, StringComparison.CurrentCultureIgnoreCase)) { var uri = new Uri(requestUrlString); string query = uri.Query; if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } Dictionary <string, string> keyPair = CoreHelpers.ParseKeyValueList(query, '&', true, false, null); string responseHeader = DeviceAuthHelper.GetBypassChallengeResponse(keyPair); var newRequest = (NSMutableUrlRequest)request.MutableCopy(); newRequest.Url = new NSUrl(keyPair["SubmitUrl"]); newRequest[BrokerConstants.ChallengeResponseHeader] = responseHeader; webView.MainFrame.LoadRequest(newRequest); WebView.DecideIgnore(decisionToken); return; } if (!request.Url.AbsoluteString.Equals("about:blank", StringComparison.CurrentCultureIgnoreCase) && !request.Url.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase)) { var result = AuthorizationResult.FromStatus( AuthorizationStatus.ErrorHttp, MsalError.NonHttpsRedirectNotSupported, MsalErrorMessage.NonHttpsRedirectNotSupported); _callbackMethod(result); WebView.DecideIgnore(decisionToken); Close(); } WebView.DecideUse(decisionToken); }
public void GetEmbeddedResourceContentsAsync_Success() { var fileContents = CoreHelpers.GetEmbeddedResourceContentsAsync("data.embeddedResource.txt"); Assert.Equal("Contents of embeddedResource.txt\n", fileContents.Replace("\r\n", "\n")); }
protected override void OnCreate(Bundle savedInstanceState) { var eventUploadIntent = new Intent(this, typeof(EventUploadReceiver)); _eventUploadPendingIntent = PendingIntent.GetBroadcast(this, 0, eventUploadIntent, PendingIntentFlags.UpdateCurrent); var alarmIntent = new Intent(this, typeof(LockAlarmReceiver)); _vaultTimeoutAlarmPendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent); var clearClipboardIntent = new Intent(this, typeof(ClearClipboardAlarmReceiver)); _clearClipboardPendingIntent = PendingIntent.GetBroadcast(this, 0, clearClipboardIntent, PendingIntentFlags.UpdateCurrent); var policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build(); StrictMode.SetThreadPolicy(policy); _deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService"); _messagingService = ServiceContainer.Resolve <IMessagingService>("messagingService"); _broadcasterService = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService"); _userService = ServiceContainer.Resolve <IUserService>("userService"); _appIdService = ServiceContainer.Resolve <IAppIdService>("appIdService"); _storageService = ServiceContainer.Resolve <IStorageService>("storageService"); _eventService = ServiceContainer.Resolve <IEventService>("eventService"); TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; UpdateTheme(ThemeManager.GetTheme(true)); base.OnCreate(savedInstanceState); if (!CoreHelpers.InDebugMode()) { Window.AddFlags(Android.Views.WindowManagerFlags.Secure); } #if !FDROID var appCenterHelper = new AppCenterHelper(_appIdService, _userService); var appCenterTask = appCenterHelper.InitAsync(); #endif Xamarin.Essentials.Platform.Init(this, savedInstanceState); Xamarin.Forms.Forms.Init(this, savedInstanceState); _appOptions = GetOptions(); LoadApplication(new App.App(_appOptions)); _broadcasterService.Subscribe(_activityKey, (message) => { if (message.Command == "scheduleVaultTimeoutTimer") { var alarmManager = GetSystemService(AlarmService) as AlarmManager; var vaultTimeoutMinutes = (int)message.Data; var vaultTimeoutMs = vaultTimeoutMinutes * 60000; var triggerMs = Java.Lang.JavaSystem.CurrentTimeMillis() + vaultTimeoutMs + 10; alarmManager.Set(AlarmType.RtcWakeup, triggerMs, _vaultTimeoutAlarmPendingIntent); } else if (message.Command == "cancelVaultTimeoutTimer") { var alarmManager = GetSystemService(AlarmService) as AlarmManager; alarmManager.Cancel(_vaultTimeoutAlarmPendingIntent); } else if (message.Command == "startEventTimer") { StartEventAlarm(); } else if (message.Command == "stopEventTimer") { var task = StopEventAlarmAsync(); } else if (message.Command == "finishMainActivity") { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish()); } else if (message.Command == "listenYubiKeyOTP") { ListenYubiKey((bool)message.Data); } else if (message.Command == "updatedTheme") { RestartApp(); } else if (message.Command == "exit") { ExitApp(); } else if (message.Command == "copiedToClipboard") { var task = ClearClipboardAlarmAsync(message.Data as Tuple <string, int?, bool>); } }); }
[InlineData(null, null)] // null public void ObfuscateEmail_Success(string input, string expected) { Assert.Equal(expected, CoreHelpers.ObfuscateEmail(input)); }
public async Task <Client> FindClientByIdAsync(string clientId) { if (!_globalSettings.SelfHosted && clientId.StartsWith("installation.")) { var idParts = clientId.Split('.'); if (idParts.Length > 1 && Guid.TryParse(idParts[1], out Guid id)) { var installation = await _installationRepository.GetByIdAsync(id); if (installation != null) { return(new Client { ClientId = $"installation.{installation.Id}", RequireClientSecret = true, ClientSecrets = { new Secret(installation.Key.Sha256()) }, AllowedScopes = new string[] { "api.push", "api.licensing" }, AllowedGrantTypes = GrantTypes.ClientCredentials, AccessTokenLifetime = 3600 * 24, Enabled = installation.Enabled, Claims = new List <ClientClaim> { new ClientClaim(JwtClaimTypes.Subject, installation.Id.ToString()) } }); } } } else if (_globalSettings.SelfHosted && clientId.StartsWith("internal.") && CoreHelpers.SettingHasValue(_globalSettings.InternalIdentityKey)) { var idParts = clientId.Split('.'); if (idParts.Length > 1) { var id = idParts[1]; if (!string.IsNullOrWhiteSpace(id)) { return(new Client { ClientId = $"internal.{id}", RequireClientSecret = true, ClientSecrets = { new Secret(_globalSettings.InternalIdentityKey.Sha256()) }, AllowedScopes = new string[] { "internal" }, AllowedGrantTypes = GrantTypes.ClientCredentials, AccessTokenLifetime = 3600 * 24, Enabled = true, Claims = new List <ClientClaim> { new ClientClaim(JwtClaimTypes.Subject, id) } }); } } } else if (clientId.StartsWith("organization.")) { var idParts = clientId.Split('.'); if (idParts.Length > 1 && Guid.TryParse(idParts[1], out var id)) { var org = await _organizationRepository.GetByIdAsync(id); if (org != null) { return(new Client { ClientId = $"organization.{org.Id}", RequireClientSecret = true, ClientSecrets = { new Secret(org.ApiKey.Sha256()) }, AllowedScopes = new string[] { "api.organization" }, AllowedGrantTypes = GrantTypes.ClientCredentials, AccessTokenLifetime = 3600 * 1, Enabled = org.Enabled && org.UseApi, Claims = new List <ClientClaim> { new ClientClaim(JwtClaimTypes.Subject, org.Id.ToString()) } }); } } } return(_apiClients.ContainsKey(clientId) ? _apiClients[clientId] : null); }
public JsonResult GetVersion() { return(Json(CoreHelpers.GetVersion())); }