58 lines
2.7 KiB
C#
58 lines
2.7 KiB
C#
// SPDX-License-Identifier: MPL-2.0
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace OpenGenesisLINK.SysApi;
|
|
|
|
/// <summary>
|
|
/// Local root-readable portal machine credential. Never log it or return it to a browser.
|
|
/// Portal deployment can receive the credential through an authorized, secure channel.
|
|
/// </summary>
|
|
public static class PortalSecretStore
|
|
{
|
|
private const string Variable = "OGL_SYSAPI_PORTAL_TOKEN";
|
|
|
|
public static string OpenOrCreate(string folder)
|
|
{
|
|
if (OperatingSystem.IsWindows())
|
|
throw new PlatformNotSupportedException("Windows credential-file ACL provisioning must be implemented before enabling SysApi");
|
|
folder = Path.GetFullPath(folder);
|
|
if (Directory.Exists(folder) && (File.GetAttributes(folder) & FileAttributes.ReparsePoint) != 0)
|
|
throw new IOException("Symlink secret directory rejected");
|
|
Directory.CreateDirectory(folder);
|
|
File.SetUnixFileMode(folder, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
|
string path = Path.Combine(folder, ".env");
|
|
if (File.Exists(path))
|
|
{
|
|
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
|
|
throw new IOException("Symlink secret file rejected");
|
|
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
string[] matches = File.ReadAllLines(path, Encoding.UTF8)
|
|
.Where(v => v.StartsWith(Variable + "=", StringComparison.Ordinal)).ToArray();
|
|
if (matches.Length != 1)
|
|
throw new IOException("Existing credential file does not contain exactly one portal token");
|
|
string existing = matches[0][(Variable.Length + 1)..].Trim();
|
|
if (existing.Length != 128 || !existing.All(Uri.IsHexDigit))
|
|
throw new IOException("Existing portal token is invalid; manual rotation is required");
|
|
return existing;
|
|
}
|
|
|
|
string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(64)).ToLowerInvariant();
|
|
// CreateNew guarantees that an existing credential is never silently overwritten.
|
|
try
|
|
{
|
|
using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
|
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
byte[] data = Encoding.UTF8.GetBytes(Variable + "=" + token + Environment.NewLine);
|
|
file.Write(data);
|
|
file.Flush(flushToDisk: true);
|
|
return token;
|
|
}
|
|
catch (IOException) when (File.Exists(path))
|
|
{
|
|
// Concurrent startup: reread the exact same persisted secret.
|
|
return OpenOrCreate(folder);
|
|
}
|
|
}
|
|
}
|