Files

294 lines
8.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
)
type AccessPolicy struct {
WorkspaceRoots []string `json:"workspaceRoots"`
TaskRules []string `json:"taskRules"`
}
var assembleRule = regexp.MustCompile(`^:?(?:[A-Za-z0-9_]+:)*assemble[A-Za-z0-9_]*\*$`)
func validTaskRule(rule string) bool {
return safeTask.MatchString(rule) || assembleRule.MatchString(rule)
}
func (p AccessPolicy) validate() error {
for _, root := range p.WorkspaceRoots {
if !filepath.IsAbs(root) {
return fmt.Errorf("工程根目录必须是绝对路径:%s", root)
}
}
for _, rule := range p.TaskRules {
if !validTaskRule(rule) {
return fmt.Errorf("非法任务规则:%s;支持完整任务名或限定模块的 assemble*", rule)
}
}
return nil
}
func readAccessPolicy(path string) (AccessPolicy, error) {
var p AccessPolicy
f, e := os.Open(path)
if e != nil {
return p, e
}
defer f.Close()
decoder := json.NewDecoder(io.LimitReader(f, 1<<20))
decoder.DisallowUnknownFields()
if e = decoder.Decode(&p); e != nil {
return p, e
}
var extra any
if e = decoder.Decode(&extra); e != io.EOF {
return p, fmt.Errorf("访问配置必须只包含一个 JSON 对象")
}
return p, p.validate()
}
func writeAccessPolicy(path string, p AccessPolicy) error {
if e := p.validate(); e != nil {
return e
}
if info, e := os.Lstat(path); e == nil && !info.Mode().IsRegular() {
return fmt.Errorf("访问配置必须为普通文件")
}
data, e := json.MarshalIndent(p, "", " ")
if e != nil {
return e
}
f, e := os.CreateTemp(filepath.Dir(path), ".access-*.tmp")
if e != nil {
return e
}
temp := f.Name()
defer os.Remove(temp)
if _, e = f.Write(append(data, '\n')); e != nil {
f.Close()
return e
}
if e = f.Sync(); e != nil {
f.Close()
return e
}
if e = f.Close(); e != nil {
return e
}
if e = preserveAccessOwnership(temp, path); e != nil {
return e
}
return os.Rename(temp, path)
}
func accessLock(path string) (func(), error) {
lock := path + ".lock"
if e := os.Mkdir(lock, 0700); e != nil {
return nil, fmt.Errorf("不能锁定访问配置(可能有其他管理命令正在执行):%s:%w", lock, e)
}
return func() { _ = os.Remove(lock) }, nil
}
func (s *Server) initAccessPolicy(path string) error {
s.accessFile = path
if e := os.MkdirAll(filepath.Dir(path), 0700); e != nil {
return e
}
unlock, e := accessLock(path)
if e != nil {
return e
}
defer unlock()
if _, e = os.Stat(path); os.IsNotExist(e) {
tasks := []string{}
for task := range s.tasks {
tasks = append(tasks, task)
}
sort.Strings(tasks)
if e = writeAccessPolicy(path, AccessPolicy{s.allowedWorkspaceRoots(), tasks}); e != nil {
return e
}
} else if e != nil {
return e
}
return s.reloadAccessPolicy()
}
func (s *Server) reloadAccessPolicy() error {
if s.accessFile == "" {
return nil
}
p, e := readAccessPolicy(s.accessFile)
if e != nil {
return fmt.Errorf("访问配置读取失败:%s:%w;请在服务器本机检查配置文件,修复前拒绝新请求", s.accessFile, e)
}
s.workspaceRoots = p.WorkspaceRoots
s.workspaceRoot = ""
s.accessLoaded = true
s.tasks = map[string]bool{}
for _, task := range p.TaskRules {
s.tasks[task] = true
}
return nil
}
func (s *Server) taskAllowed(task string) bool {
if !safeTask.MatchString(task) {
return false
}
if s.tasks[task] {
return true
}
for rule := range s.tasks {
if assembleRule.MatchString(rule) && strings.HasPrefix(task, strings.TrimSuffix(rule, "*")) {
return true
}
}
return false
}
// CLI has no HTTP equivalent: the caller must have local filesystem permission.
func runAdmin(args []string, out io.Writer) error {
fs := flag.NewFlagSet("remotecompile admin", flag.ContinueOnError)
fs.SetOutput(out)
data := fs.String("data", "", "自定义服务数据目录;省略时自动定位本机已安装服务")
config := fs.String("access-file", "", "自定义访问配置;默认 <data>/access.json")
fs.Usage = func() {
fmt.Fprintln(out, "用法:remotecompile admin [--data <服务数据目录>] [--access-file <配置>] root|task add|remove|list [值]\n示例:task add ':app:assemble*';root add <已有绝对目录>\n命令需要服务器本机权限;运行中的0.4.8及以上服务自动读取配置,无需重启。")
fs.PrintDefaults()
}
if e := fs.Parse(args); e != nil {
return e
}
rest := fs.Args()
if len(rest) < 2 || (rest[0] != "root" && rest[0] != "task") || (rest[1] != "add" && rest[1] != "remove" && rest[1] != "list") {
fs.Usage()
return fmt.Errorf("无效的管理命令")
}
if (rest[1] == "list" && len(rest) != 2) || (rest[1] != "list" && len(rest) != 3) {
return fmt.Errorf("add/remove 需要一个值,list 不需要值")
}
path := *config
if path == "" {
if *data != "" {
path = filepath.Join(*data, "access.json")
} else {
var locateErr error
path, locateErr = localAccessFile()
if locateErr != nil {
return locateErr
}
}
}
path, e := filepath.Abs(path)
if e != nil {
return e
}
if rest[1] == "list" {
p, e := readAccessPolicy(path)
if e != nil {
return fmt.Errorf("不能读取 %s:%w;首次请先启动0.4.8服务自动迁移原配置", path, e)
}
return json.NewEncoder(out).Encode(p)
}
unlock, e := accessLock(path)
if e != nil {
return e
}
defer unlock()
p, e := readAccessPolicy(path)
if e != nil {
return fmt.Errorf("不能读取 %s:%w;请确认 --data 与服务配置一致,且0.4.8服务已完成首次启动", path, e)
}
value := rest[2]
var values *[]string
if rest[0] == "root" {
if !filepath.IsAbs(value) {
return fmt.Errorf("目录必须为绝对路径")
}
value = filepath.Clean(value)
if rest[1] == "add" {
st, e := os.Lstat(value)
if e != nil {
return e
}
if !st.IsDir() || st.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("请选择已有普通目录")
}
real, e := filepath.EvalSymlinks(value)
if e != nil {
return e
}
if !sameAccessValue(real, value) {
return fmt.Errorf("目录经过符号链接或重解析路径,不允许添加")
}
}
values = &p.WorkspaceRoots
} else {
if !validTaskRule(value) {
return fmt.Errorf("非法任务规则:只允许完整任务名或 assemble* 规则,不能附带参数")
}
values = &p.TaskRules
}
next := []string{}
found := false
for _, v := range *values {
equal := v == value
if rest[0] == "root" {
equal = sameAccessValue(v, value)
}
if equal {
found = true
if rest[1] == "remove" {
continue
}
}
next = append(next, v)
}
if rest[1] == "add" && !found {
next = append(next, value)
}
*values = next
if e = writeAccessPolicy(path, p); e != nil {
return e
}
fmt.Fprintf(out, "已保存:%s %s %s\n配置:%s\n运行中的服务会在下一次请求生效,无需重启。\n", rest[0], rest[1], value, path)
if rest[0] == "root" && rest[1] == "add" {
fmt.Fprintln(out, "此命令仅授权目录范围,不修改操作系统ACL;请在插件点击检查远程工程验证服务账户读写权限。")
}
return nil
}
func sameAccessValue(a, b string) bool {
if runtime.GOOS == "windows" {
return strings.EqualFold(a, b)
}
return a == b
}
func (s *Server) adminCommand(kind, value string) string {
exe, e := os.Executable()
if e != nil {
exe = "remotecompile"
}
quote := func(v string) string { return "'" + strings.ReplaceAll(v, "'", `'"'"'`) + "'" }
prefix := "sudo "
if runtime.GOOS == "windows" {
prefix = "& "
quote = func(v string) string { return "'" + strings.ReplaceAll(v, "'", "''") + "'" }
}
location := "--data " + quote(s.root)
if detected, err := localAccessFile(); err == nil && s.accessFile != "" && sameAccessValue(detected, s.accessFile) {
location = ""
}
if s.accessFile != "" && s.accessFile != filepath.Join(s.root, "access.json") {
location += " --access-file " + quote(s.accessFile)
}
return prefix + quote(exe) + " admin " + strings.TrimSpace(location+" "+kind) + " add " + quote(value)
}
func (s *Server) rootAccessError(path string) error {
return fmt.Errorf("目录未在服务端允许范围内:%s\n请在服务器本机以管理员权限执行(授权该目录及其子目录):\n%s\n然后在插件重新检查工程;CLI 不会创建目录或自动修改系统权限", path, s.adminCommand("root", path))
}