public static async Task <NodeDebuggerStatus> TrySetupNodeDebuggerAsync() { try { var existingLaunchJson = await(FileSystemHelpers.FileExists(LaunchJsonPath) ? TaskUtilities.SafeGuardAsync(async() => JsonConvert.DeserializeObject <VsCodeLaunch>(await FileSystemHelpers.ReadAllTextFromFileAsync(LaunchJsonPath))) : Task.FromResult <VsCodeLaunch>(null)); FileSystemHelpers.CreateDirectory(Path.GetDirectoryName(LaunchJsonPath)); if (existingLaunchJson == null) { await FileSystemHelpers.WriteAllTextToFileAsync(LaunchJsonPath, JsonConvert.SerializeObject(DefaultLaunchJson, Formatting.Indented)); return(NodeDebuggerStatus.Created); } var functionsDebugConfig = existingLaunchJson.Configurations .FirstOrDefault(c => c.Type.Equals("node", StringComparison.OrdinalIgnoreCase) && c.Request.Equals("attach", StringComparison.OrdinalIgnoreCase)); if (functionsDebugConfig == null) { existingLaunchJson.Configurations = existingLaunchJson.Configurations.Concat(DefaultLaunchJson.Configurations); await FileSystemHelpers.WriteAllTextToFileAsync(LaunchJsonPath, JsonConvert.SerializeObject(existingLaunchJson, Formatting.Indented)); return(NodeDebuggerStatus.Updated); } else { return(NodeDebuggerStatus.AlreadyCreated); } } catch (Exception e) { if (Environment.GetEnvironmentVariable(Constants.CliDebug) == "1") { ColoredConsole.Error.WriteLine(ErrorColor(e.ToString())); } return(NodeDebuggerStatus.Error); } }
public IEnumerable <LogEntry> GetLogEntryDetails(string id, string entryId) { ITracer tracer = _traceFactory.GetTracer(); using (tracer.Step($"DeploymentManager.GetLogEntryDetails(id:{id}, entryId:{entryId}")) { string path = GetLogPath(id, ensureDirectory: false); if (!FileSystemHelpers.FileExists(path)) { throw new FileNotFoundException(String.Format(CultureInfo.CurrentCulture, Resources.Error_NoLogFound, id)); } VerifyDeployment(id, IsDeploying); var logger = GetLoggerForFile(path); return(logger.GetLogEntryDetails(entryId).ToList()); } }
public static DeploymentStatusFile Open(string id, IEnvironment environment, IOperationLock statusLock) { return(statusLock.LockOperation(() => { string path = Path.Combine(environment.DeploymentsPath, id, StatusFile); XDocument document = null; if (!FileSystemHelpers.FileExists(path)) { return null; } using (var stream = FileSystemHelpers.OpenRead(path)) { document = XDocument.Load(stream); } return new DeploymentStatusFile(id, environment, statusLock, document); }, DeploymentStatusManager.LockTimeout)); }
public static string GetFunctionAppRootDirectory(string startingDirectory) { var hostJson = Path.Combine(startingDirectory, ScriptConstants.HostMetadataFileName); if (FileSystemHelpers.FileExists(hostJson)) { return(startingDirectory); } var parent = Path.GetDirectoryName(startingDirectory); if (parent == null) { throw new CliException($"Unable to find function project root. Expecting to have {ScriptConstants.HostMetadataFileName} in function project root."); } else { return(GetFunctionAppRootDirectory(parent)); } }
public override async Task RunAsync() { if (!string.IsNullOrEmpty(FolderName)) { var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName); FileSystemHelpers.EnsureDirectory(folderPath); Environment.CurrentDirectory = folderPath; } if (!Platforms.Contains(Platform)) { ColoredConsole.Error.WriteLine(ErrorColor($"platform {Platform} is not supported. Valid options are: {String.Join(",", Platforms)}")); return; } var dockerFilePath = Path.Combine(Environment.CurrentDirectory, "Dockerfile"); if (!FileSystemHelpers.FileExists(dockerFilePath)) { ColoredConsole.Error.WriteLine(ErrorColor($"Dockerfile not found in directory {Environment.CurrentDirectory}")); return; } var image = $"{Registry}/{Name}-azurefunc"; ColoredConsole.WriteLine("Building Docker image..."); await DockerHelpers.DockerBuild(image, Environment.CurrentDirectory); ColoredConsole.WriteLine("Pushing function image to registry..."); await DockerHelpers.DockerPush(image); var platform = PlatformFactory.CreatePlatform(Platform, ConfigPath); if (platform == null) { ColoredConsole.Error.WriteLine(ErrorColor($"Platform {Platform} is not supported")); return; } await platform.DeployContainerizedFunction(Name, image, MinInstances, MaxInstances); }
public void SetPrivateKey(string key) { ITracer tracer = _traceFactory.GetTracer(); using (tracer.Step("SSHKeyManager.SetPrivateKey")) { FileSystemHelpers.EnsureDirectory(_sshPath); // Delete existing public key if (FileSystemHelpers.FileExists(_id_rsaPub)) { FileSystemHelpers.DeleteFileSafe(_id_rsaPub); } // bypass service key checking prompt (StrictHostKeyChecking=no). FileSystemHelpers.WriteAllText(_config, ConfigContent); // This overrides if file exists FileSystemHelpers.WriteAllText(_id_rsa, key); } }
public static async Task <string> EnsureExtensionsProjectExistsAsync(ISecretsManager secretsManager, bool csx, string extensionsDir = null) { if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.dotnet && !csx) { return(DotnetHelpers.GetCsprojOrFsproj()); } if (String.IsNullOrEmpty(extensionsDir)) { extensionsDir = Environment.CurrentDirectory; } var extensionsProj = Path.Combine(extensionsDir, Constants.ExtenstionsCsProjFile); if (!FileSystemHelpers.FileExists(extensionsProj)) { FileSystemHelpers.EnsureDirectory(extensionsDir); await FileSystemHelpers.WriteAllTextToFileAsync(extensionsProj, await StaticResources.ExtensionsProject); } return(extensionsProj); }
private string GetActiveDeploymentManifestPath() { string id = _status.ActiveDeploymentId; // We've seen rare cases of corruption where the file is full of NUL characters. // If we see the first char is 0, treat the file as corrupted and ignore it if (String.IsNullOrEmpty(id) || id[0] == 0) { return(null); } string manifestPath = GetDeploymentManifestPath(id); // If the manifest file doesn't exist, don't return it as it could confuse kudusync. // This can happen if the deployment was created with just metadata but no actualy deployment took place. if (!FileSystemHelpers.FileExists(manifestPath)) { return(null); } return(manifestPath); }
private DiagnosticsSettings ReadSettings() { if (FileSystemHelpers.FileExists(_path)) { try { string fileContent = null; OperationManager.Attempt(() => fileContent = FileSystemHelpers.ReadAllTextFromFile(_path)); return(JsonConvert.DeserializeObject <DiagnosticsSettings>(fileContent)); } catch (Exception ex) { _tracer.TraceError(ex); // there must be corrupted value, delete file to reset everything to default FileSystemHelpers.DeleteFileSafe(_path); } } return(new DiagnosticsSettings()); }
internal static async Task <System.Diagnostics.TraceLevel> GetTraceLevel(string scriptPath) { var filePath = Path.Combine(scriptPath, ScriptConstants.HostMetadataFileName); if (!FileSystemHelpers.FileExists(filePath)) { return(DefaultTraceLevel); } var hostJson = JsonConvert.DeserializeObject <JObject>(await FileSystemHelpers.ReadAllTextFromFileAsync(filePath)); var traceLevelStr = hostJson["tracing"]?["consoleLevel"]?.ToString(); if (!string.IsNullOrEmpty(traceLevelStr) && Enum.TryParse(traceLevelStr, true, out System.Diagnostics.TraceLevel traceLevel)) { return(traceLevel); } else { return(DefaultTraceLevel); } }
private async Task <string> GetFunctionTestData(string functionName, FunctionTestData packageLimit) { string testDataFilePath = GetFunctionTestDataFilePath(functionName); // Create an empty file if it doesn't exist if (!FileSystemHelpers.FileExists(testDataFilePath)) { FileSystemHelpers.WriteAllText(testDataFilePath, String.Empty); } if (packageLimit != null) { var fileSize = FileSystemHelpers.FileInfoFromFileName(testDataFilePath).Length; if (!packageLimit.DeductFromBytesLeftInPackage(fileSize)) { return($"Test_Data is of size {fileSize} bytes, but there's only {packageLimit.BytesLeftInPackage} bytes left in ARM response"); } } return(await FileSystemHelpers.ReadAllTextFromFileAsync(testDataFilePath)); }
public static TJobStatus ReadJobStatusFromFile <TJobStatus>(ITraceFactory traceFactory, string statusFilePath) where TJobStatus : class, IJobStatus { try { if (!FileSystemHelpers.FileExists(statusFilePath)) { return(null); } return(OperationManager.Attempt(() => { string content = FileSystemHelpers.ReadAllTextFromFile(statusFilePath).Trim(); return JsonConvert.DeserializeObject <TJobStatus>(content, JsonSerializerSettings); })); } catch (Exception ex) { traceFactory.GetTracer().TraceError(ex); return(null); } }
protected void InitializeJobInstance(JobBase job, IJobLogger logger) { if (!String.Equals(JobName, job.Name, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( "The job runner can only run jobs with the same name it was configured, configured - {0}, trying to run - {1}".FormatInvariant( JobName, job.Name)); } if (!FileSystemHelpers.FileExists(job.ScriptFilePath)) { throw new InvalidOperationException("Missing job script to run - {0}".FormatInvariant(job.ScriptFilePath)); } CacheJobBinaries(logger); if (WorkingDirectory == null) { throw new InvalidOperationException("Missing working directory"); } }
public static async Task <Stream> GetAppZipFile(string functionAppRoot, bool buildNativeDeps, BuildOption buildOption, bool noBuild, GitIgnoreParser ignoreParser = null, string additionalPackages = null, bool ignoreDotNetCheck = false) { var gitIgnorePath = Path.Combine(functionAppRoot, Constants.FuncIgnoreFile); if (ignoreParser == null && FileSystemHelpers.FileExists(gitIgnorePath)) { ignoreParser = new GitIgnoreParser(await FileSystemHelpers.ReadAllTextFromFileAsync(gitIgnorePath)); } if (noBuild) { ColoredConsole.WriteLine(Yellow("Skipping build event for functions project (--no-build).")); } else if (buildOption == BuildOption.Remote) { ColoredConsole.WriteLine(Yellow("Performing remote build for functions project.")); } else if (buildOption == BuildOption.Local) { ColoredConsole.WriteLine(Yellow("Performing local build for functions project.")); } if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.python && !noBuild) { return(await PythonHelpers.GetPythonDeploymentPackage(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser), functionAppRoot, buildNativeDeps, buildOption, additionalPackages)); } else if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.dotnet && !ignoreDotNetCheck && !noBuild && buildOption != BuildOption.Remote) { throw new CliException("Pack command doesn't work for dotnet functions"); } else if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.dotnet && buildOption == BuildOption.Remote) { // Remote build for dotnet does not require bin and obj folders. They will be generated during the oryx build return(await CreateZip(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser, false, new string[] { "bin", "obj" }), functionAppRoot)); } else { return(await CreateZip(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser, false), functionAppRoot)); } }
public static TJobStatus ReadJobStatusFromFile <TJobStatus>(IAnalytics analytics, string statusFilePath) where TJobStatus : class, IJobStatus { try { if (!FileSystemHelpers.FileExists(statusFilePath)) { return(null); } // since we don't have proper lock on file, we are more forgiving in retry (10 times 250 ms interval). return(OperationManager.Attempt(() => { string content = FileSystemHelpers.ReadAllTextFromFile(statusFilePath).Trim(); return JsonConvert.DeserializeObject <TJobStatus>(content, JsonSerializerSettings); }, retries: 10)); } catch (Exception ex) { analytics.UnexpectedException(ex); return(null); } }
public static async Task <Stream> GetAppZipFile(WorkerRuntime workerRuntime, string functionAppRoot, bool buildNativeDeps, bool noBundler, GitIgnoreParser ignoreParser = null, string additionalPackages = null, bool ignoreDotNetCheck = false) { var gitIgnorePath = Path.Combine(functionAppRoot, Constants.FuncIgnoreFile); if (ignoreParser == null && FileSystemHelpers.FileExists(gitIgnorePath)) { ignoreParser = new GitIgnoreParser(await FileSystemHelpers.ReadAllTextFromFileAsync(gitIgnorePath)); } if (workerRuntime == WorkerRuntime.python) { return(await PythonHelpers.GetPythonDeploymentPackage(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser), functionAppRoot, buildNativeDeps, noBundler, additionalPackages)); } else if (workerRuntime == WorkerRuntime.dotnet && !ignoreDotNetCheck) { throw new CliException("Pack command doesn't work for dotnet functions"); } else { return(CreateZip(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser), functionAppRoot)); } }
public static async Task <Stream> GetAppZipFile(WorkerRuntime workerRuntime, string functionAppRoot, GitIgnoreParser ignoreParser = null) { var gitIgnorePath = Path.Combine(functionAppRoot, Constants.FuncIgnoreFile); if (ignoreParser == null && FileSystemHelpers.FileExists(gitIgnorePath)) { ignoreParser = new GitIgnoreParser(await FileSystemHelpers.ReadAllTextFromFileAsync(gitIgnorePath)); } if (workerRuntime == WorkerRuntime.python) { return(await PythonHelpers.GetPythonDeploymentPackage(GetLocalFiles(functionAppRoot, ignoreParser), functionAppRoot)); } else if (workerRuntime == WorkerRuntime.dotnet) { throw new CliException("Pack command doesn't work for dotnet functions"); } else { return(CreateZip(GetLocalFiles(functionAppRoot, ignoreParser), functionAppRoot)); } }
protected override string DetermineSecurityProtocol(JObject payload) { JObject repository = payload.Value <JObject>("repository"); string repositoryUrl = repository.Value <string>("url"); bool isPrivate = repository.Value <bool>("private"); if (isPrivate) { repositoryUrl = repository.Value <string>("ssh_url"); } else if (!String.Equals(new Uri(repositoryUrl).Host, "github.com", StringComparison.OrdinalIgnoreCase)) { if (_environment != null && FileSystemHelpers.FileExists(Path.Combine(_environment.SSHKeyPath, PrivateKeyFile))) { // if we determine that a github request does not come from "github.com" // and it is not a private repository, but we still find a ssh key, we assume // the request is from a private GHE repositoryUrl = repository.Value <string>("ssh_url"); } } return(repositoryUrl); }
private void SetLocalInfo(SiteExtensionInfo info) { string localPath = GetInstallationDirectory(info.Id); if (FileSystemHelpers.DirectoryExists(localPath)) { info.LocalPath = localPath; info.InstalledDateTime = FileSystemHelpers.GetLastWriteTimeUtc(info.LocalPath); } if (ExtensionRequiresApplicationHost(info)) { info.ExtensionUrl = FileSystemHelpers.FileExists(Path.Combine(localPath, Constants.ApplicationHostXdtFileName)) ? GetFullUrl(GetUrlFromApplicationHost(info)) : null; } else { info.ExtensionUrl = String.IsNullOrEmpty(info.LocalPath) ? null : GetFullUrl(info.ExtensionUrl); } info.FeedUrl = GetSettingManager(info.Id).GetValue(_feedUrlSetting); }
/// <summary> /// Gets an existing created public key or creates a new one and returns the public key /// </summary> public string GetPublicKey(bool ensurePublicKey) { ITracer tracer = _traceFactory.GetTracer(); using (tracer.Step("SSHKeyManager.GetKey")) { if (FileSystemHelpers.FileExists(_id_rsaPub)) { tracer.Trace("Public key exists."); // If a public key exists, return it. return(FileSystemHelpers.ReadAllText(_id_rsaPub)); } else if (ensurePublicKey) { tracer.Trace("Creating key pair."); return(CreateKeyPair()); } // A public key does not exist but we weren't asked to create it. return(null); } }
public static string GetValue(string key, string defaultValue = null) { var configs = _configs; if (configs == null || DateTime.UtcNow > _configsTTL) { _configsTTL = DateTime.UtcNow.AddMinutes(10); try { var settings = FileSystemHelpers.FileExists(_configsFile) ? FileSystemHelpers.ReadAllText(_configsFile) : null; KuduEventSource.Log.GenericEvent( ServerConfiguration.GetApplicationName(), $"ScmHostingConfigurations: Update value '{settings}'", string.Empty, string.Empty, string.Empty, string.Empty); configs = Parse(settings); _configs = configs; } catch (Exception ex) { KuduEventSource.Log.KuduException( ServerConfiguration.GetApplicationName(), "ScmHostingConfigurations.GetValue", string.Empty, string.Empty, $"ScmHostingConfigurations: Fail to GetValue('{key}')", ex.ToString()); } } return((configs == null || !configs.TryGetValue(key, out string value)) ? defaultValue : value); }
public static async Task <string> EnsureExtensionsProjectExistsAsync() { var extensionsProj = Path.Combine(Environment.CurrentDirectory, "extensions.csproj"); if (!FileSystemHelpers.FileExists(extensionsProj)) { var assembly = typeof(ExtensionsHelper).Assembly; var extensionsProjText = string.Empty; using (Stream resource = assembly.GetManifestResourceStream(assembly.GetName().Name + ".ExtensionsProj.txt")) using (var reader = new StreamReader(resource)) { while (!reader.EndOfStream) { var line = await reader.ReadLineAsync(); extensionsProjText += $"{line}{Environment.NewLine}"; } } await FileSystemHelpers.WriteAllTextToFileAsync(extensionsProj, extensionsProjText); } return(extensionsProj); }
private void SetLocalInfo(SiteExtensionInfo info) { string localPath = GetInstallationDirectory(info.Id); if (FileSystemHelpers.DirectoryExists(localPath)) { info.LocalPath = localPath; info.InstalledDateTime = FileSystemHelpers.GetLastWriteTimeUtc(info.LocalPath); } if (ExtensionRequiresApplicationHost(info)) { if (FileSystemHelpers.FileExists(Path.Combine(localPath, _applicationHostFile))) { info.ExtensionUrl = GetUrlFromApplicationHost(info); } else { info.ExtensionUrl = null; } if (info.Type == SiteExtensionInfo.SiteExtensionType.PreInstalledNonKudu) { info.Version = GetLatestPreInstalledExtensionVersion(info.Id); } } else { if (!String.IsNullOrEmpty(info.LocalPath)) { info.ExtensionUrl = _baseUrl + info.ExtensionUrl + "/"; } else { info.ExtensionUrl = null; } } }
/// <summary> /// Ensures smooth transition between mono based Kudu and KuduLite. /// <remarks> /// <list type="bullet"> /// <item> /// POST Receive GitHook File:This file was previously hard coded with mono path to launch kudu console. /// </item> /// <item> /// We will would use the OryxBuild in future for deployments, as a safety measure we clear /// the deployment script. /// </item> /// </list> /// </remarks> /// </summary> /// <param name="environment"></param> internal static void MigrateToNetCorePatch(IEnvironment environment) { // Get the repository path: // Use value in the settings.xml file if it is present. string repositoryPath = environment.RepositoryPath; IDeploymentSettingsManager settings = GetDeploymentSettingsManager(environment); if (settings != null) { var settingsRepoPath = DeploymentSettingsExtension.GetRepositoryPath(settings); repositoryPath = Path.Combine(environment.SiteRootPath, settingsRepoPath); } var gitPostReceiveHookFile = Path.Combine(repositoryPath, ".git", "hooks", "post-receive"); if (FileSystemHelpers.FileExists(gitPostReceiveHookFile)) { var fileText = FileSystemHelpers.ReadAllText(gitPostReceiveHookFile); var isRunningOnAzure = System.Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID") != null; if (fileText.Contains("/usr/bin/mono")) { if (isRunningOnAzure) { FileSystemHelpers.WriteAllText(gitPostReceiveHookFile, fileText.Replace("/usr/bin/mono", "benv dotnet=2.2 dotnet")); } } else if (!fileText.Contains("benv") && fileText.Contains("dotnet") && isRunningOnAzure) { FileSystemHelpers.WriteAllText(gitPostReceiveHookFile, fileText.Replace("dotnet", "benv dotnet=2.2 dotnet")); } } if (FileSystemHelpers.DirectoryExists(Path.Combine(environment.RootPath, ".mono")) && FileSystemHelpers.FileExists(Path.Combine(environment.DeploymentToolsPath, "deploy.sh"))) { FileSystemHelpers.DeleteFileSafe(Path.Combine(environment.DeploymentToolsPath, "deploy.sh")); } }
public static async Task <string> EnsureExtensionsProjectExistsAsync(ISecretsManager secretsManager, bool csx, string extensionsDir = null) { var workerRuntime = WorkerRuntimeLanguageHelper.GetCurrentWorkerRuntimeLanguage(secretsManager); if (workerRuntime == WorkerRuntime.dotnet && !csx) { return(DotnetHelpers.GetCsproj()); } if (String.IsNullOrEmpty(extensionsDir)) { extensionsDir = Environment.CurrentDirectory; } var extensionsProj = Path.Combine(extensionsDir, "extensions.csproj"); if (!FileSystemHelpers.FileExists(extensionsProj)) { FileSystemHelpers.EnsureDirectory(extensionsDir); await FileSystemHelpers.WriteAllTextToFileAsync(extensionsProj, await StaticResources.ExtensionsProject); } return(extensionsProj); }
private void AddFilesToZip(ZipArchive zip) { foreach (var path in _paths) { if (Directory.Exists(path)) { var dir = new DirectoryInfo(path); if (path.EndsWith(Constants.LogFilesPath, StringComparison.Ordinal)) { foreach (var info in dir.GetFileSystemInfos()) { var directoryInfo = info as DirectoryInfo; if (directoryInfo != null) { // excluding FREB as it contains user sensitive data such as authorization header if (!info.Name.StartsWith("W3SVC", StringComparison.OrdinalIgnoreCase)) { zip.AddDirectory(directoryInfo, _tracer, Path.Combine(dir.Name, info.Name)); } } else { zip.AddFile((FileInfo)info, _tracer, dir.Name); } } } else { zip.AddDirectory(dir, _tracer, Path.GetFileName(path)); } } else if (FileSystemHelpers.FileExists(path)) { zip.AddFile(path, _tracer, String.Empty); } } }
public static async Task EnsureVirtualEnvrionmentIgnored() { if (InVirtualEnvironment) { try { var virtualEnvName = Path.GetFileNameWithoutExtension(VirtualEnvironmentPath); if (FileSystemHelpers.DirectoryExists(Path.Join(Environment.CurrentDirectory, virtualEnvName))) { var funcIgnorePath = Path.Join(Environment.CurrentDirectory, Constants.FuncIgnoreFile); // If .funcignore exists and already has the venv name, we are done here if (FileSystemHelpers.FileExists(funcIgnorePath)) { var rawfuncIgnoreContents = await FileSystemHelpers.ReadAllTextFromFileAsync(funcIgnorePath); if (rawfuncIgnoreContents.Contains(Environment.NewLine + virtualEnvName)) { return; } } // Write the current env to .funcignore ColoredConsole.WriteLine($"Writing {Constants.FuncIgnoreFile}"); using (var fileStream = FileSystemHelpers.OpenFile(funcIgnorePath, FileMode.Append, FileAccess.Write)) using (var streamWriter = new StreamWriter(fileStream)) { await streamWriter.WriteAsync(Environment.NewLine + virtualEnvName); await streamWriter.FlushAsync(); } } } catch (Exception) { // Safe execution, we aren't harmed by failures here } } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { var context = new HttpContextWrapper(HttpContext.Current); var isFile = FileSystemHelpers.FileExists(HostingEnvironment.MapPath($"~{context.Request.Url.AbsolutePath.Replace('/', '\\')}")); var route = RouteTable.Routes.GetRouteData(context); // If the route is not registerd in the WebAPI RouteTable // then it's not an API route, which means it's a resource (*.js, *.css, *.cshtml), not authenticated. // If the route doesn't have authenticated value assume true var isAuthenticated = route != null && (route.Values["authenticated"] == null || (bool)route.Values["authenticated"]); // In some cases, context.Request.RawUrl may not be populated, but context.Request.UrlReferrer will be populated. // context.Request.UrlReferrer = null evals to true, is okay in this case var isTryPageRequested = context.Request.RawUrl.StartsWith("/try", StringComparison.OrdinalIgnoreCase); if (!isFile && //skip auth for files !isTryPageRequested && //when requesting /try users can be unauthenticated !SecurityManager.TryAuthenticateRequest(context)) // and if the user is not loggedon { if (isAuthenticated) { context.Response.Headers["LoginUrl"] = SecurityManager.GetLoginUrl(context); context.Response.StatusCode = 403; // Forbidden } else if (context.Request.Url.AbsolutePath.Equals("/api/health", StringComparison.OrdinalIgnoreCase)) { context.Response.WriteFile(HostingEnvironment.MapPath("~/health.html")); context.Response.Flush(); context.Response.End(); } else if (!isFile && !context.Request.RawUrl.StartsWith("/api/")) { context.Response.RedirectLocation = Environment.GetEnvironmentVariable("ACOM_MARKETING_PAGE") ?? $"{context.Request.Url.GetLeftPart(UriPartial.Authority)}/signin"; context.Response.StatusCode = 302; context.Response.End(); } } }
internal static async Task <Stream> GetPythonDeploymentPackage(IEnumerable <string> files, string functionAppRoot, bool buildNativeDeps, string additionalPackages) { if (!FileSystemHelpers.FileExists(Path.Combine(functionAppRoot, Constants.RequirementsTxt))) { throw new CliException($"{Constants.RequirementsTxt} is not found. " + $"{Constants.RequirementsTxt} is required for python function apps. Please make sure to generate one before publishing."); } if (buildNativeDeps) { if (CommandChecker.CommandExists("docker") && await DockerHelpers.VerifyDockerAccess()) { return(await InternalPreparePythonDeploymentInDocker(files, functionAppRoot, additionalPackages)); } else { throw new CliException("Docker is required to build native dependencies for python function apps"); } } else { return(await InternalPreparePythonDeployment(files, functionAppRoot)); } }
public static bool IsDefaultWebRootContent(string webroot) { if (!FileSystemHelpers.DirectoryExists(webroot)) { // degenerated return(true); } var entries = FileSystemHelpers.GetFileSystemEntries(webroot); if (entries.Length == 0) { // degenerated return(true); } if (entries.Length == 1 && FileSystemHelpers.FileExists(entries[0])) { string hoststarthtml = Path.Combine(webroot, Constants.HostingStartHtml); return(String.Equals(entries[0], hoststarthtml, StringComparison.OrdinalIgnoreCase)); } return(false); }