节点在线、应用在线、配置在线使用令牌查询
大石头 authored at 2021-12-16 19:49:30
7.10 KiB
Stardust
using Microsoft.AspNetCore.Mvc;
using NewLife;
using NewLife.Log;
using NewLife.Remoting;
using NewLife.Remoting.Extensions;
using NewLife.Remoting.Services;
using Stardust.Data;
using Stardust.Models;
using Stardust.Server.Services;

namespace Stardust.Server.Controllers;

/// <summary>StarAgent远程部署服务</summary>
[ApiFilter]
[Route("[controller]/[action]")]
public class AgentDeployController(AgentDeployService deployService, ITokenService tokenService, ITracer tracer) : ControllerBase
{
    /// <summary>验证调用方。远程部署把服务器当作SSH跳板,仅允许已配置密钥且具控制权的管理应用(如StarWeb)调用</summary>
    /// <returns>通过校验的应用</returns>
    private App Valid()
    {
        var token = ApiFilterAttribute.GetToken(HttpContext);
        if (token.IsNullOrEmpty()) throw new ApiException(ApiCode.Unauthorized, L.T("No token provided."));

        var (jwt, ex) = tokenService.DecodeToken(token);
        if (ex != null) throw ex;

        var app = App.FindByName(jwt?.Subject);
        if (app == null || !app.Enable) throw new ApiException(ApiCode.Unauthorized, L.T("Invalid application token"));

        // 空密钥应用可被匿名冒用(如种子StarWeb),禁止使用远程部署等高危能力
        if (app.Secret.IsNullOrEmpty())
            throw new ApiException(ApiCode.Forbidden, L.T("[{0}] has no secret configured; remote deployment is forbidden. Set a Secret for this application in the registry.", app));

        // 仅具控制权的管理应用(配置了AllowControlNodes)可远程部署
        if (app.AllowControlNodes.IsNullOrEmpty())
            throw new ApiException(ApiCode.Forbidden, L.T("[{0}] has no control permission; remote deployment is forbidden.", app));

        return app;
    }

    /// <summary>执行远程部署</summary>
    /// <param name="model">部署参数</param>
    /// <returns>部署结果</returns>
    [HttpPost]
    public List<AgentDeployResult> Deploy([FromBody] AgentDeployModel model)
    {
        Valid();

        // 凭据不入链路标签
        using var span = tracer?.NewSpan("AgentDeploy-Deploy", new { model.Hosts, model.Port, model.UserName, model.OSType, model.AuthMode, model.Sudo, model.ServerUrl });

        try
        {
            XTrace.WriteLine(L.TLog("Received remote deployment request: Hosts={0}, User={1}, OS={2}, Server={3}", model.Hosts, model.UserName, model.OSType, model.ServerUrl));

            var results = deployService.Deploy(model);

            var success = results.Count(r => r.Success);
            var failed = results.Count - success;

            XTrace.WriteLine(L.TLog("Deployment completed: succeeded={0}, failed={1}", success, failed));

            return results;
        }
        catch (Exception ex)
        {
            span?.SetError(ex, null);
            XTrace.WriteException(ex);
            throw;
        }
    }

    /// <summary>测试连接。凭据改走 POST JSON body(task-95 二期 N3,2026-11-12 lead 批:与 WebApi 宿主同语义);
    /// 旧行为=query-only 简单参数绑定,凭据随 URL 落访问日志/链路。DTO 同文件定义(Stardust.Models 共享模型不涉)。</summary>
    /// <param name="model">连接参数(body)</param>
    /// <returns>连接测试结果</returns>
    [HttpPost]
    public Object TestConnection([FromBody] TestConnectionModel model)
    {
        Valid();

        var host = model?.Host;
        var port = model?.Port ?? 0;
        var userName = model?.UserName;

        if (host.IsNullOrEmpty()) throw new ArgumentNullException(nameof(host));
        if (userName.IsNullOrEmpty()) throw new ArgumentNullException(nameof(userName));
        if (model!.UsePrivateKey())
        {
            if (model.PrivateKey.IsNullOrEmpty()) throw new ArgumentNullException(nameof(model.PrivateKey));
        }
        else if (model.Password.IsNullOrEmpty()) throw new ArgumentNullException(nameof(model.Password));

        String? keyFile = null;
        try
        {
            // 尝试SSH连接并执行echo命令。密码走 SSHPASS 环境变量,私钥落临时文件,命令行不出现凭据
            keyFile = model.UsePrivateKey() ? AgentDeployService.PrepareKeyFile(model.PrivateKey) : null;

            var auth = keyFile.IsNullOrEmpty() ? "sshpass -e " : "";
            var options = keyFile.IsNullOrEmpty()
                ? "-o StrictHostKeyChecking=no -o ConnectTimeout=10"
                : $"-i '{keyFile}' -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=10";
            var cmd = $"{auth}ssh -p {port} {options} {userName}@{host} 'echo connected'";

            var psi = new System.Diagnostics.ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = $"-c \"{cmd.Replace("\"", "\\\"")}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            if (keyFile.IsNullOrEmpty() && !model.Password.IsNullOrEmpty()) psi.Environment["SSHPASS"] = model.Password;

            using var process = System.Diagnostics.Process.Start(psi);
            if (process == null) return new { success = false, message = L.T("Unable to start the process.") };

            var output = process.StandardOutput.ReadToEnd();
            var error = process.StandardError.ReadToEnd();

            if (!process.WaitForExit(15000))
            {
                process.Kill();
                return new { success = false, message = L.T("Connection timed out.") };
            }

            if (process.ExitCode == 0 && output.Contains("connected"))
            {
                return new { success = true, message = L.T("Connected.") };
            }
            else
            {
                return new { success = false, message = L.T("Connection failed: {0}", error) };
            }
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
            return new { success = false, message = ex.Message };
        }
        finally
        {
            if (keyFile != null)
            {
                try { System.IO.File.Delete(keyFile); } catch { }
            }
        }
    }
}

/// <summary>连接测试参数(task-95 二期 N3:凭据走 body 不入查询串;WebApi 宿主转发同 JSON 形态)</summary>
public class TestConnectionModel
{
    /// <summary>目标主机</summary>
    public String Host { get; set; } = null!;

    /// <summary>SSH端口</summary>
    public Int32 Port { get; set; }

    /// <summary>用户名</summary>
    public String UserName { get; set; } = null!;

    /// <summary>密码。认证方式为密码时必填</summary>
    public String? Password { get; set; }

    /// <summary>认证方式。Password按密码登录,PrivateKey按私钥登录</summary>
    public String AuthMode { get; set; } = "Password";

    /// <summary>SSH私钥。认证方式为 PrivateKey 时使用</summary>
    public String? PrivateKey { get; set; }

    /// <summary>是否私钥认证</summary>
    public Boolean UsePrivateKey() => AuthMode.EqualIgnoreCase("PrivateKey");
}