mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-03 07:15:22 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cb6b6489e | ||
|
|
0cc501bba4 | ||
|
|
f367ce618e | ||
|
|
e4077066ef | ||
|
|
8c53c3c741 | ||
|
|
d8c4607b60 | ||
|
|
f9580a7c23 | ||
|
|
7fcbbcab0b | ||
|
|
2de0bf029d | ||
|
|
17d7bebf88 | ||
|
|
1432c7176b | ||
|
|
426225bd14 | ||
|
|
518d836c7b |
@@ -15,7 +15,7 @@
|
||||
"@fontsource/ibm-plex-mono": "5.3.0",
|
||||
"@fontsource/ibm-plex-sans": "5.3.0",
|
||||
"@fortawesome/free-solid-svg-icons": "7.3.1",
|
||||
"@perfect-design/ui": "0.3.10",
|
||||
"@perfect-design/ui": "0.4.0",
|
||||
"axios": "^1.20.0",
|
||||
"pinia": "^4.0.0",
|
||||
"vue": "^3.5.26",
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@testing-library/jest-dom": "^7.0.0",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/vue": "^8.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
|
||||
Generated
+172
-447
File diff suppressed because it is too large
Load Diff
@@ -3,13 +3,13 @@ module github.com/lukaszraczylo/gohoarder
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go-v2 v1.48.0
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.21
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.3
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.0
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.24
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.6
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1
|
||||
github.com/cloudsoda/go-smb2 v0.0.0-20261105190815-95be04a983b8
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
github.com/go-sql-driver/mysql v1.10.2
|
||||
github.com/go-sql-driver/mysql v1.11.0
|
||||
github.com/goccy/go-json v0.12.0
|
||||
github.com/gofiber/fiber/v3 v3.7.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -37,20 +37,20 @@ require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
|
||||
github.com/aws/smithy-go v1.28.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.14.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.3 // indirect
|
||||
github.com/aws/smithy-go v1.28.11 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
@@ -71,8 +71,8 @@ require (
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/gofiber/schema v1.10.0 // indirect
|
||||
github.com/gofiber/utils/v2 v2.6.5 // indirect
|
||||
github.com/gofiber/schema v1.11.1 // indirect
|
||||
github.com/gofiber/utils/v2 v2.6.6 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.4 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
@@ -100,7 +100,7 @@ require (
|
||||
github.com/moby/moby/client v0.6.3 // indirect
|
||||
github.com/moby/patternmatcher v0.6.1 // indirect
|
||||
github.com/moby/sys/sequential v0.7.0 // indirect
|
||||
github.com/moby/sys/user v0.5.0 // indirect
|
||||
github.com/moby/sys/user v0.5.1 // indirect
|
||||
github.com/moby/sys/userns v0.2.1 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/molecule-man/go-brrr v1.3.1 // indirect
|
||||
@@ -125,7 +125,7 @@ require (
|
||||
github.com/tklauser/go-sysconf v0.4.0 // indirect
|
||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.79.0 // indirect
|
||||
github.com/valyala/fasthttp v1.81.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
|
||||
|
||||
@@ -8,42 +8,42 @@ github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 h1:m2xcjRABtG288
|
||||
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4/go.mod h1:MTUE7ZuZO89FAtAwozGg6AWD83pcdefnEq5gF82MB8s=
|
||||
github.com/Microsoft/go-winio v0.6.4 h1:kJF2pamtYCWXf0xAT8sAkwKC0pMl2HYBrRPHAqyUc+g=
|
||||
github.com/Microsoft/go-winio v0.6.4/go.mod h1:1xl5JXG4ze/m74GH6Dc4Mwxfc3VL5siRVQjIAlHH07U=
|
||||
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
|
||||
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.21 h1:NY1d3yXmplUSYnUAue0sR88svD+SJiaI+YJGp8TxSNg=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.21/go.mod h1:pVJNXUXaCLu9a/4/liTklg9zR3yO0xm/XBEQhgg5nzc=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.3 h1:bh+9VoJ4eDzJVEY6jfdNTBa0Dx7tdr+lWSPNovU1vXc=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.3/go.mod h1:4CNs0EBvjDEpyaXSYCdNeNRhFjHFX2Y373tFUaeTYXA=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 h1:oH1E0tjN0g+ZRusbX1dsuat4FJ0z05l8hWaycSbDuNc=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9/go.mod h1:3ZaQGigIoaS45x9HgnLZ4sP475Fs7QoxU3IsZX/J3h4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.0 h1:0/glEMW6lLpeGOq7tDKn3314ookbLSvzRs71Oknt6gA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.0/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 h1:bIEk1HfTd3MGzvDa5YOQUodGr96D9+UTnmBLBB8ZJ10=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.14.0/go.mod h1:LdwHjKqPE9VCC7sTlWcOAizZx3ZJYjmfwC/EW2tIIAE=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 h1:ANAoa+qt3/9kXnvQVgUyxcTzhzZf4DqaBS+M2DQrELU=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5/go.mod h1:vsMi+SSR7xGQXtV430LVi49qbv/R+U+upHHSp1W/+QI=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy9etdz+RKTeqzchXErAI=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
|
||||
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
|
||||
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 h1:LfdRwpJ0Dfh+vpqHevmmnFnMoc3/lfB4pdHOfWpLfH4=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29/go.mod h1:r6fijnrGRQ4OnSGyHYuFcC7G6wdwB4Ld8WhiIaGZHx0=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.24 h1:MUbmPfgy01NrN+HS37o9iIkDw3j3E5QRcbmgltv1+aA=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.24/go.mod h1:myVUWoiDQr3tZmTHhN9qiALVM8QW2LF3qhobW5D7VRo=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.6 h1:EFGg+hghWKZTqy/1DHqCGsnKAgATAPPfVSwSMErOeqo=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.6/go.mod h1:MU//4Jnc2473mFZGIt/ZZDCuZxf4O1i241E1taXijc4=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.12 h1:iVrZnlJUz886rp/2yOWxK+AbtR8ZwVNVO2kE3//Bgc8=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.12/go.mod h1:fLzXWXb9TJfRF5BzXeQaX6FInXezaQq8Uz0BRmMGuUE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 h1:D2smhPZgqVLuc8rmuvb6wrG4sgut9iv1BN8W2twFtfo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16/go.mod h1:HheOgBYcgoZgeKSLVEmk9whxHERlVXAKTVWK3xizKeo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 h1:5w2E7ndu7XOt62yvu2vGm/Rv7WDn1oQjrJ7Dt1NTVTM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15/go.mod h1:1WgfBCsJYL6E7T2QkkE8kQvo7uG+5+z2LpaQ9L6pjZs=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1 h1:fOeEIKMlgwKbMFSNMM+pLo2NPRJ1dSKbaAuZYGXUVR0=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1/go.mod h1:xHaAZkbYuIc9UtLZxdoeyhzmx06g1paDjPkHgljJU/I=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.14.3 h1:iWgA/aDj99JAb3VO5PWw9iF5weoTQm7wxLEMT0Ex/MY=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.14.3/go.mod h1:7YfGlRtvWLx6EfPOM89plg0AcIyuFqOHhfK2iMCOI34=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.8 h1:0fKFg9h8VR5qEHNgDn7CRMvYSsZHl0sBsMyeWsF6YXc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.8/go.mod h1:0zVH+3FrAkRJ7da4EBDyfEGKTsvXK3sgyjw7FnohF3g=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.8 h1:SDuU4vlszzKfTlvNejSjcP1bye5vcrgZF6Ru3hybNsU=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.8/go.mod h1:Un05dkqLD6qwNJCHqtXiAWkj+2lKJ4aeXaAy/3fdrEA=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.3 h1:v32GRL6ljBqK/xk7SAnbmFGpgNBb5G4J/EbZqG62Pjg=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.3/go.mod h1:3skcGfglqLhKpz95YNfXrpAZAFZz8OYkj/MH5JxDxkI=
|
||||
github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI=
|
||||
github.com/aws/smithy-go v1.28.11/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
@@ -97,18 +97,18 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/go-sql-driver/mysql v1.10.2 h1:5TRvGvczDohUMOCRA5aCAXgfSZOo/oNDSFD/2RrChS0=
|
||||
github.com/go-sql-driver/mysql v1.10.2/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/go-sql-driver/mysql v1.11.0 h1:0dFnuu2mR7g+8Smo/rL18y1WnTLgVrHttzSahf20Gb4=
|
||||
github.com/go-sql-driver/mysql v1.11.0/go.mod h1:evJsoGjlO/9BFsnfXyjtluDYb3OSGzPNOnUaBl/2Dao=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
|
||||
github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
|
||||
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
|
||||
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
|
||||
github.com/gofiber/schema v1.10.0 h1:d/2/NpHOVD0f29aNvM3KSPmaEDLJZvxW5edtN4Ymd8U=
|
||||
github.com/gofiber/schema v1.10.0/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
|
||||
github.com/gofiber/utils/v2 v2.6.5 h1:rU+8ao6LKi3fKOA3sEjfLv1T+2C2IwomeVmEKaqkr4A=
|
||||
github.com/gofiber/utils/v2 v2.6.5/go.mod h1:OqPxdhDW7fPz0dupDanqf4e5O15IyFKy724y/EY9RI4=
|
||||
github.com/gofiber/schema v1.11.1 h1:yVcBkGBbOkbDEgBBRQNEWop0uIldWM9hkfwxqHju9sA=
|
||||
github.com/gofiber/schema v1.11.1/go.mod h1:I/XJCYksHGxe1zGTGH+v7EKyljGdahwQPlf1Cj0/Fqk=
|
||||
github.com/gofiber/utils/v2 v2.6.6 h1:sQh7xRZSzcq6WG/l311J4GTbeJy0AcSf+9MEo8t6350=
|
||||
github.com/gofiber/utils/v2 v2.6.6/go.mod h1:AcFb3ONJbN3XKoJbDGJ3+lpZ4TFku9GGehB7cWMeic4=
|
||||
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/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -187,8 +187,8 @@ github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9Kou
|
||||
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
|
||||
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
|
||||
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
|
||||
github.com/moby/sys/user v0.5.0 h1:5+S4lyoavGyX1DGs68NW8xpx48T9+a7ogSUc0KjZg8Y=
|
||||
github.com/moby/sys/user v0.5.0/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
|
||||
github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0=
|
||||
github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
|
||||
github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8=
|
||||
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
@@ -225,8 +225,8 @@ github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
|
||||
github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
|
||||
github.com/shamaton/msgpack/v3 v3.2.7 h1:YuVYjZq5+NLIREdW52txCmEfVGIi4ithcdhOJhAmU5A=
|
||||
github.com/shamaton/msgpack/v3 v3.2.7/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo=
|
||||
github.com/shamaton/msgpack/v3 v3.3.0 h1:2DwmAIaapfeCSPOF0JKTK1BsUr0nsi4qT6y2zMU3gbg=
|
||||
github.com/shamaton/msgpack/v3 v3.3.0/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo=
|
||||
github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg=
|
||||
github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk=
|
||||
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
|
||||
@@ -271,8 +271,8 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
|
||||
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.79.0 h1:32ur91W4kWG+1s6x3oDlP8/KNmjlZZlUzSSC4p9LSWE=
|
||||
github.com/valyala/fasthttp v1.79.0/go.mod h1:NQN+PlgP93+JRPnCiApN5XwnI24oMQf8kuzrxtsTy9A=
|
||||
github.com/valyala/fasthttp v1.81.0 h1:/mTcnzriVgu17nQU2yKQp0Z53EQcmP6mmH4DNuUC0Eo=
|
||||
github.com/valyala/fasthttp v1.81.0/go.mod h1:dP2CcfIhdN6jmScbPXp6gQvSky6pe0gPT5Lybo9SBIE=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
|
||||
+15
-10
@@ -184,6 +184,7 @@ type SecurityConfig struct {
|
||||
RescanConcurrency int `mapstructure:"rescan_concurrency" json:"rescan_concurrency"` // scans run in parallel per rescan cycle; <1 = 1
|
||||
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
|
||||
ScanWaitTimeout time.Duration `mapstructure:"scan_wait_timeout" json:"scan_wait_timeout"` // how long a first download waits for its scan; 0 = 30s
|
||||
MinFreeBytes int64 `mapstructure:"min_free_bytes" json:"min_free_bytes"` // defer scans while the temp dir has less free space; 0 = off
|
||||
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
|
||||
@@ -213,9 +214,10 @@ type ScannersConfig struct {
|
||||
|
||||
// TrivyConfig contains Trivy scanner configuration
|
||||
type TrivyConfig struct {
|
||||
CacheDB string `mapstructure:"cache_db" json:"cache_db"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
CacheDB string `mapstructure:"cache_db" json:"cache_db"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
DBUpdateInterval time.Duration `mapstructure:"db_update_interval" json:"db_update_interval"` // 0 = 6h
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
}
|
||||
|
||||
// OSVConfig contains OSV scanner configuration
|
||||
@@ -236,8 +238,9 @@ type StaticConfig struct {
|
||||
|
||||
// GrypeConfig contains Grype scanner configuration
|
||||
type GrypeConfig struct {
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
DBUpdateInterval time.Duration `mapstructure:"db_update_interval" json:"db_update_interval"` // must stay under grype's 120h max database age; 0 = 6h
|
||||
}
|
||||
|
||||
// GovulncheckConfig contains govulncheck scanner configuration
|
||||
@@ -408,9 +411,10 @@ func Default() *Config {
|
||||
},
|
||||
Scanners: ScannersConfig{
|
||||
Trivy: TrivyConfig{
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
CacheDB: "/var/lib/trivy",
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
CacheDB: "/var/lib/trivy",
|
||||
DBUpdateInterval: 6 * time.Hour,
|
||||
},
|
||||
OSV: OSVConfig{
|
||||
Enabled: false,
|
||||
@@ -424,8 +428,9 @@ func Default() *Config {
|
||||
BlockSuspicious: false,
|
||||
},
|
||||
Grype: GrypeConfig{
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
DBUpdateInterval: 6 * time.Hour,
|
||||
},
|
||||
Govulncheck: GovulncheckConfig{
|
||||
Enabled: false,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Package dbrefresh runs a scanner's vulnerability database update on a fixed interval.
|
||||
package dbrefresh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// DefaultInterval applies when the configured interval is 0.
|
||||
const DefaultInterval = 6 * time.Hour
|
||||
|
||||
// Run calls update every interval until stop closes. immediate runs the first update at once;
|
||||
// otherwise it waits one interval.
|
||||
func Run(stop <-chan struct{}, interval time.Duration, immediate bool, scanner string, update func(context.Context) error) {
|
||||
if interval <= 0 {
|
||||
interval = DefaultInterval
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
<-stop
|
||||
cancel()
|
||||
}()
|
||||
|
||||
once := func() {
|
||||
if err := update(ctx); err != nil {
|
||||
log.Error().Err(err).Str("scanner", scanner).Msg("Scheduled database update failed")
|
||||
}
|
||||
}
|
||||
if immediate {
|
||||
once()
|
||||
}
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
once()
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type diskProbeScanner struct {
|
||||
stubScanner
|
||||
calls int
|
||||
}
|
||||
|
||||
func (c *diskProbeScanner) Scan(ctx context.Context, registry, packageName, version, path string) (*metadata.ScanResult, error) {
|
||||
c.calls++
|
||||
return c.stubScanner.Scan(ctx, registry, packageName, version, path)
|
||||
}
|
||||
|
||||
func diskGuardManager(t *testing.T, minFree int64, free uint64, freeErr error) (*Manager, *stubMetadataStore, *diskProbeScanner) {
|
||||
t.Helper()
|
||||
store := &stubMetadataStore{}
|
||||
mgr, err := New(config.SecurityConfig{Enabled: true, MinFreeBytes: minFree, ScanRetryInterval: time.Hour}, store)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(mgr.Stop)
|
||||
mgr.freeBytes = func(string) (uint64, error) { return free, freeErr }
|
||||
s := &diskProbeScanner{stubScanner: *stubResult("trivy", metadata.ScanStatusClean, nil)}
|
||||
mgr.RegisterScanner(s)
|
||||
return mgr, store, s
|
||||
}
|
||||
|
||||
func TestScanIsDeferredWhenDiskIsLow(t *testing.T) {
|
||||
mgr, store, s := diskGuardManager(t, 1<<30, 1<<20, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Zero(t, s.calls, "no scanner may run on a full disk")
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusError, store.savedResults[0].Status)
|
||||
assert.Equal(t, true, store.savedResults[0].Details[DetailInfrastructureError], "low disk is retried, not blamed on the package")
|
||||
}
|
||||
|
||||
func TestScanRunsWhenDiskHasRoom(t *testing.T) {
|
||||
mgr, store, s := diskGuardManager(t, 1<<30, 2<<30, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusClean, store.savedResults[0].Status)
|
||||
}
|
||||
|
||||
func TestDiskGuardOffByDefault(t *testing.T) {
|
||||
mgr, _, s := diskGuardManager(t, 0, 0, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
}
|
||||
|
||||
func TestDiskGuardMeasurementFailureDoesNotBlockScans(t *testing.T) {
|
||||
mgr, _, s := diskGuardManager(t, 1<<30, 0, errors.New("statfs failed"))
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var errLowDiskSpace = stderrors.New("not enough free disk space to scan")
|
||||
|
||||
// checkDiskSpace refuses a scan while the temp dir, where scanners unpack packages, is short
|
||||
// of space. A failed measurement never blocks scans.
|
||||
func (m *Manager) checkDiskSpace() error {
|
||||
if m.config.MinFreeBytes <= 0 || m.freeBytes == nil {
|
||||
return nil
|
||||
}
|
||||
dir := os.TempDir()
|
||||
free, err := m.freeBytes(dir)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot measure free disk space")
|
||||
return nil
|
||||
}
|
||||
if need := uint64(m.config.MinFreeBytes); free < need {
|
||||
return fmt.Errorf("%w: %d bytes free in %s, need %d", errLowDiskSpace, free, dir, need)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func diskFree(path string) (uint64, error) {
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(path, &st); err != nil {
|
||||
return 0, fmt.Errorf("statfs %s: %w", path, err)
|
||||
}
|
||||
return st.Bavail * uint64(st.Bsize), nil // #nosec G115 -- block size is never negative
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -79,18 +80,25 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
fmt.Sprintf("not a module path and version: %q %q", module, version), ""), nil
|
||||
}
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "govulncheck-*")
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
tmpDir, err := os.MkdirTemp(wd.Path(), "govulncheck-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
|
||||
// govulncheck never reports advisories against the main module of the tree it scans, so
|
||||
// scanning the module's own source reports a vulnerable module clean. The module is
|
||||
// scanned as a dependency of a wrapper module instead, and the wrapper imports its
|
||||
// packages because module-mode scanning only considers modules that provide an import.
|
||||
// Resolving the module reaches the module proxy.
|
||||
env := append(os.Environ(), "GOFLAGS=-mod=mod", "GOTOOLCHAIN=local", "GOWORK=off")
|
||||
// The dependency tree goes to a module cache inside tmpDir, so the scan keeps nothing on disk;
|
||||
// -modcacherw leaves that cache writable, or RemoveAll cannot delete it.
|
||||
env := append(wd.Env(os.Environ()), "GOFLAGS=-mod=mod -modcacherw", "GOTOOLCHAIN=local", "GOWORK=off",
|
||||
"GOMODCACHE="+filepath.Join(tmpDir, "modcache"))
|
||||
goMod := fmt.Sprintf("module gohoarder.audit\n\nrequire %s %s\n", module, version)
|
||||
if err = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte(goMod), 0o600); err != nil {
|
||||
return nil, fmt.Errorf("failed to write go.mod: %w", err)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
@@ -132,7 +133,7 @@ func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
|
||||
env, err := os.ReadFile(filepath.Join(rec, "env")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-mod=mod|local\n", string(env))
|
||||
assert.Equal(t, "-mod=mod -modcacherw|local\n", string(env))
|
||||
|
||||
assert.Equal(t, []string{"-json", "-scan", "module"}, scannertest.Args(t, args))
|
||||
|
||||
@@ -144,6 +145,32 @@ func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
assert.NotContains(t, imports, "/internal", "internal packages cannot be imported")
|
||||
}
|
||||
|
||||
func TestScanRemovesTheModulesItDownloaded(t *testing.T) {
|
||||
rec := t.TempDir()
|
||||
// Like go, the fake leaves the module cache read-only unless GOFLAGS has -modcacherw.
|
||||
scannertest.Script(t, "go", fmt.Sprintf(`
|
||||
[ -n "$GOMODCACHE" ] || exit 1
|
||||
mkdir -p "$GOMODCACHE/example.com/[email protected]"
|
||||
touch "$GOMODCACHE/example.com/[email protected]/dep.go"
|
||||
case "$GOFLAGS" in *-modcacherw*) ;; *) chmod 0555 "$GOMODCACHE/example.com/[email protected]" ;; esac
|
||||
echo "$GOMODCACHE" > %q/go
|
||||
echo "github.com/google/uuid uuid 12 0 "`, rec))
|
||||
scannertest.Script(t, "govulncheck", fmt.Sprintf(`
|
||||
echo "$GOMODCACHE" > %q/govulncheck
|
||||
cat %q`, rec, abs(t, "google-uuid-v1.6.0.stream")))
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
listCache, err := os.ReadFile(filepath.Join(rec, "go")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
scanCache, err := os.ReadFile(filepath.Join(rec, "govulncheck")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(listCache), string(scanCache), "govulncheck reads the modules go list downloaded")
|
||||
assert.NoDirExists(t, strings.TrimSpace(string(listCache)), "the scan keeps no downloaded modules")
|
||||
}
|
||||
|
||||
func TestScanCleanModule(t *testing.T) {
|
||||
scannertest.Script(t, "go", `echo "github.com/google/uuid uuid 12 0 "`)
|
||||
_, _ = fakeGovulncheck(t, abs(t, "google-uuid-v1.6.0.stream"), 0, "")
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/dbrefresh"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
// grype's own limits are 30s for the update check and 5m for the download.
|
||||
dbUpdateTimeout = 10 * time.Minute
|
||||
// Far past dbUpdateTimeout, so only a download whose grype process died is removed.
|
||||
abandonedAfter = time.Hour
|
||||
|
||||
downloadPrefix = "grype-db-download"
|
||||
// go-getter, which grype downloads through, stages the archive in the temp dir.
|
||||
getterPrefix = "getter"
|
||||
)
|
||||
|
||||
// RefreshDatabase updates the database every interval until stop closes. immediate runs
|
||||
// the first update at once; otherwise it waits one interval. interval 0 means 6h.
|
||||
func (s *Scanner) RefreshDatabase(stop <-chan struct{}, interval time.Duration, immediate bool) {
|
||||
dbrefresh.Run(stop, interval, immediate, ScannerName, s.UpdateDatabase)
|
||||
}
|
||||
|
||||
// dbCacheDir mirrors grype's db.cache-dir default and its GRYPE_DB_CACHE_DIR override.
|
||||
func dbCacheDir() (string, error) {
|
||||
if dir := os.Getenv("GRYPE_DB_CACHE_DIR"); dir != "" {
|
||||
return dir, nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, ".cache", "grype", "db"), nil
|
||||
}
|
||||
|
||||
// removeAbandonedDownloads deletes database downloads last touched before cutoff. A grype
|
||||
// process killed mid-download never removes its staging dirs.
|
||||
func removeAbandonedDownloads(cutoff time.Time) {
|
||||
if dir, err := dbCacheDir(); err != nil {
|
||||
log.Warn().Err(err).Str("scanner", ScannerName).Msg("Cannot locate the Grype database cache")
|
||||
} else {
|
||||
removeStaleDirs(dir, downloadPrefix, cutoff)
|
||||
}
|
||||
removeStaleDirs(os.TempDir(), getterPrefix, cutoff)
|
||||
}
|
||||
|
||||
func removeStaleDirs(dir, prefix string, cutoff time.Time) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot list dir for abandoned Grype downloads")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() || !strings.HasPrefix(e.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil || !info.ModTime().Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, e.Name())
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
log.Warn().Err(err).Str("path", path).Msg("Cannot remove abandoned Grype download")
|
||||
continue
|
||||
}
|
||||
log.Info().Str("path", path).Msg("Removed abandoned Grype download")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestScanDisablesDatabaseAutoUpdate(t *testing.T) {
|
||||
envFile := filepath.Join(t.TempDir(), "env")
|
||||
fix, err := filepath.Abs(fixture("purl-minimist-0.0.8.json"))
|
||||
require.NoError(t, err)
|
||||
scannertest.Script(t, "grype", "printf '%s' \"$GRYPE_DB_AUTO_UPDATE\" > '"+envFile+"'\ncat '"+fix+"'")
|
||||
|
||||
_, err = New(config.GrypeConfig{}).Scan(context.Background(), "npm", "minimist", "0.0.8", "/tmp/artifact")
|
||||
|
||||
require.NoError(t, err)
|
||||
got, err := os.ReadFile(envFile) // #nosec G304 -- test temp file
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "false", string(got), "a scan must never download the database itself")
|
||||
}
|
||||
|
||||
func mkdirAged(t *testing.T, path string, age time.Duration) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(path, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(path, "archive"), []byte("x"), 0o600))
|
||||
when := time.Now().Add(-age)
|
||||
require.NoError(t, os.Chtimes(path, when, when))
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseRemovesAbandonedDownloads(t *testing.T) {
|
||||
cacheDir, tmpDir := t.TempDir(), t.TempDir()
|
||||
t.Setenv("GRYPE_DB_CACHE_DIR", cacheDir)
|
||||
t.Setenv("TMPDIR", tmpDir)
|
||||
scannertest.Fake(t, "grype", "", "", 0)
|
||||
|
||||
mkdirAged(t, filepath.Join(cacheDir, "grype-db-download111"), 2*time.Hour)
|
||||
mkdirAged(t, filepath.Join(cacheDir, "grype-db-download222"), time.Minute)
|
||||
mkdirAged(t, filepath.Join(cacheDir, "6"), 48*time.Hour)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "getter333"), 2*time.Hour)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "getter444"), time.Minute)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "npm-audit-555"), 2*time.Hour)
|
||||
|
||||
require.NoError(t, New(config.GrypeConfig{}).UpdateDatabase(context.Background()))
|
||||
|
||||
assert.NoDirExists(t, filepath.Join(cacheDir, "grype-db-download111"))
|
||||
assert.NoDirExists(t, filepath.Join(tmpDir, "getter333"))
|
||||
assert.DirExists(t, filepath.Join(cacheDir, "grype-db-download222"), "a download in progress stays")
|
||||
assert.DirExists(t, filepath.Join(tmpDir, "getter444"), "a download in progress stays")
|
||||
assert.DirExists(t, filepath.Join(cacheDir, "6"), "the live database stays")
|
||||
assert.DirExists(t, filepath.Join(tmpDir, "npm-audit-555"), "other tools' temp dirs stay")
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseNeverOverlaps(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
lock, overlap := filepath.Join(dir, "lock"), filepath.Join(dir, "overlap")
|
||||
scannertest.Script(t, "grype",
|
||||
"mkdir '"+lock+"' 2>/dev/null || echo x >> '"+overlap+"'\nsleep 0.2\nrmdir '"+lock+"' 2>/dev/null\nexit 0")
|
||||
s := New(config.GrypeConfig{})
|
||||
|
||||
done := make(chan error, 4)
|
||||
for range 4 {
|
||||
go func() { done <- s.UpdateDatabase(context.Background()) }()
|
||||
}
|
||||
for range 4 {
|
||||
require.NoError(t, <-done)
|
||||
}
|
||||
|
||||
assert.NoFileExists(t, overlap, "two database downloads ran at once")
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseOutlivesCallerCancel(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "finished")
|
||||
scannertest.Script(t, "grype", "sleep 0.3\ntouch '"+marker+"'")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
_ = New(config.GrypeConfig{}).UpdateDatabase(ctx)
|
||||
|
||||
assert.FileExists(t, marker, "a cancelled caller must not kill the download half way")
|
||||
}
|
||||
|
||||
func TestRefreshDatabaseRunsOnInterval(t *testing.T) {
|
||||
calls := filepath.Join(t.TempDir(), "calls")
|
||||
scannertest.Script(t, "grype", "echo \"$1 $2\" >> '"+calls+"'")
|
||||
stop := make(chan struct{})
|
||||
exited := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
New(config.GrypeConfig{}).RefreshDatabase(stop, 20*time.Millisecond, true)
|
||||
close(exited)
|
||||
}()
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
data, _ := os.ReadFile(calls) // #nosec G304 -- test temp file
|
||||
return strings.Count(string(data), "db update\n") >= 3
|
||||
}, 5*time.Second, 10*time.Millisecond)
|
||||
close(stop)
|
||||
select {
|
||||
case <-exited:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("refresh loop did not stop")
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,17 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -26,6 +29,7 @@ const ScannerName = "grype"
|
||||
type Scanner struct {
|
||||
version scanver.Cache
|
||||
config config.GrypeConfig
|
||||
dbMu sync.Mutex
|
||||
}
|
||||
|
||||
// New creates a new Grype scanner
|
||||
@@ -53,7 +57,14 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
if target == "" {
|
||||
target = filePath
|
||||
}
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
cmd := exec.CommandContext(ctx, "grype", target, "-o", "json", "-q") // #nosec G204 -- target is a purl or the stored artifact path
|
||||
// Concurrent scans each downloading the database filled the disk; RefreshDatabase owns updates.
|
||||
cmd.Env = append(wd.Env(os.Environ()), "GRYPE_DB_AUTO_UPDATE=false")
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, err := cmd.Output()
|
||||
@@ -116,10 +127,17 @@ func (s *Scanner) Health(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateDatabase updates Grype's vulnerability database
|
||||
// UpdateDatabase updates Grype's vulnerability database. Calls are serialised, and the
|
||||
// download outlives a cancelled ctx so it never leaves a half-written database behind.
|
||||
func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
||||
log.Info().Str("scanner", ScannerName).Msg("Updating Grype database")
|
||||
s.dbMu.Lock()
|
||||
defer s.dbMu.Unlock()
|
||||
|
||||
log.Info().Str("scanner", ScannerName).Msg("Updating Grype database")
|
||||
removeAbandonedDownloads(time.Now().Add(-abandonedAfter))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbUpdateTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "grype", "db", "update")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package scanner_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/govulncheck"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/grype"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/npmaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/pipaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/trivy"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// trivyCache returns a trivy cache dir that already holds a database.
|
||||
func trivyCache(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(dir, "db"), 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "db", "trivy.db"), nil, 0o600))
|
||||
return dir
|
||||
}
|
||||
|
||||
type scanFunc func(ctx context.Context, registry, packageName, version, filePath string) (*metadata.ScanResult, error)
|
||||
|
||||
// A scanner binary killed by its timeout never removes its own temp files: a killed trivy
|
||||
// leaves its database download (trivy-<n>, getter<n>, up to 279 MB) in TMPDIR.
|
||||
func TestScanLeavesNothingInTheTempDir(t *testing.T) {
|
||||
const leave = `mkdir -p "$TMPDIR/trivy-1/db" "$TMPDIR/getter1" && echo x > "$TMPDIR/trivy-1/db/trivy.db"`
|
||||
cases := []struct {
|
||||
scan scanFunc
|
||||
name, bin, body string
|
||||
registry, pkg, ver string
|
||||
}{
|
||||
{name: "trivy timeout", bin: "trivy", body: leave + "\nexec sleep 5", registry: "pypi", pkg: "p", ver: "1",
|
||||
scan: trivy.New(config.TrivyConfig{Timeout: time.Second, CacheDB: trivyCache(t)}).Scan},
|
||||
{name: "grype failure", bin: "grype", body: leave + "\nexit 1", registry: "npm", pkg: "p", ver: "1.0.0",
|
||||
scan: grype.New(config.GrypeConfig{}).Scan},
|
||||
{name: "npm audit failure", bin: "npm", body: leave + "\nexit 1", registry: "npm", pkg: "p", ver: "1.0.0",
|
||||
scan: npmaudit.New(config.NpmAuditConfig{}).Scan},
|
||||
{name: "pip-audit failure", bin: "pip-audit", body: leave + "\nexit 1", registry: "pypi", pkg: "requests", ver: "2.0.0",
|
||||
scan: pipaudit.New(config.PipAuditConfig{}).Scan},
|
||||
{name: "govulncheck go list failure", bin: "go", body: leave + "\nexit 1", registry: "go", pkg: "golang.org/x/text", ver: "v0.3.5",
|
||||
scan: govulncheck.New(config.GovulncheckConfig{}).Scan},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
scannertest.Script(t, tc.bin, tc.body)
|
||||
archive := filepath.Join(t.TempDir(), "p.tgz")
|
||||
require.NoError(t, os.WriteFile(archive, []byte("x"), 0o600))
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
|
||||
_, _ = tc.scan(context.Background(), tc.registry, tc.pkg, tc.ver, archive)
|
||||
|
||||
left, err := os.ReadDir(tmp)
|
||||
require.NoError(t, err)
|
||||
names := make([]string, 0, len(left))
|
||||
for _, e := range left {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
assert.Empty(t, names)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -69,11 +70,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
Str("version", version).
|
||||
Msg("Starting npm audit scan")
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "npm-audit-*")
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
tmpDir, err := os.MkdirTemp(wd.Path(), "npm-audit-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
|
||||
if err = writeWrapper(tmpDir, packageName, filePath); err != nil {
|
||||
return s.scanErrorResult(ctx, registry, packageName, version, fmt.Sprintf("prepare audit project: %v", err), ""), nil
|
||||
@@ -95,6 +100,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
"--no-fund",
|
||||
)
|
||||
installCmd.Dir = tmpDir
|
||||
installCmd.Env = wd.Env(os.Environ())
|
||||
if installOut, installErr := installCmd.CombinedOutput(); installErr != nil {
|
||||
log.Warn().
|
||||
Err(installErr).
|
||||
@@ -107,6 +113,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
|
||||
cmd := exec.CommandContext(ctx, "npm", "audit", "--omit=dev", "--json") // #nosec G204 -- fixed args
|
||||
cmd.Dir = tmpDir
|
||||
cmd.Env = installCmd.Env
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // npm audit exits non-zero when it finds vulnerabilities
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -74,11 +75,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
fmt.Sprintf("not a project name and version: %q %q", packageName, version), ""), nil
|
||||
}
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "pip-audit-*")
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
tmpDir, err := os.MkdirTemp(wd.Path(), "pip-audit-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
|
||||
// pip-audit has no wheel or sdist input: its positional argument is a project directory. The
|
||||
// release is audited by its pinned name and version. --no-deps and --disable-pip keep it to
|
||||
@@ -89,6 +94,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, "pip-audit", "-r", reqFile, "--no-deps", "--disable-pip", "-f", "json") // #nosec G204 -- name and version are validated, file is in a controlled temp dir
|
||||
cmd.Env = wd.Env(os.Environ())
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // pip-audit exits non-zero when it finds vulnerabilities
|
||||
|
||||
+20
-2
@@ -99,6 +99,8 @@ type Manager struct {
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
fileSource FileSource
|
||||
freeBytes func(path string) (uint64, error)
|
||||
stopCh chan struct{}
|
||||
inflight map[string]int
|
||||
scanners []Scanner
|
||||
config config.SecurityConfig
|
||||
@@ -113,10 +115,13 @@ func (m *Manager) Enabled() bool {
|
||||
return m.enabled
|
||||
}
|
||||
|
||||
// Stop cancels pending scan retries.
|
||||
// Stop cancels pending scan retries and background database refreshes.
|
||||
func (m *Manager) Stop() {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
if !m.stopped && m.stopCh != nil {
|
||||
close(m.stopCh)
|
||||
}
|
||||
m.stopped = true
|
||||
for key, timer := range m.retryTimers {
|
||||
timer.Stop()
|
||||
@@ -212,6 +217,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
metadataStore: metadataStore,
|
||||
retryTimers: make(map[string]*time.Timer),
|
||||
inflight: make(map[string]int),
|
||||
freeBytes: diskFree,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
if !cfg.Enabled {
|
||||
@@ -231,6 +238,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
log.Warn().Err(err).Msg("Failed to update Trivy database on startup")
|
||||
}
|
||||
}
|
||||
// Scans never update the database, so without this loop it ages past its NextUpdate.
|
||||
go trivyScanner.RefreshDatabase(manager.stopCh, cfg.Scanners.Trivy.DBUpdateInterval, !cfg.UpdateDBOnStartup)
|
||||
}
|
||||
|
||||
// Initialize OSV scanner
|
||||
@@ -252,6 +261,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
log.Warn().Err(err).Msg("Failed to update Grype database on startup")
|
||||
}
|
||||
}
|
||||
// Scans never update the database, so without this loop it ages past grype's limit.
|
||||
go grypeScanner.RefreshDatabase(manager.stopCh, cfg.Scanners.Grype.DBUpdateInterval, !cfg.UpdateDBOnStartup)
|
||||
}
|
||||
|
||||
// Initialize govulncheck scanner
|
||||
@@ -324,7 +335,14 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
scannerNames := make([]string, 0)
|
||||
var infraFailures, otherFailures int
|
||||
|
||||
for _, scanner := range m.scanners {
|
||||
scanners := m.scanners
|
||||
if err := m.checkDiskSpace(); err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Msg("Deferring security scan")
|
||||
infraFailures++
|
||||
scanners = nil
|
||||
}
|
||||
|
||||
for _, scanner := range scanners {
|
||||
// Skip scanners that don't support this registry
|
||||
if !m.shouldRunScanner(scanner.Name(), registry) {
|
||||
log.Debug().
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package trivy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// withDB returns cfg with a cache dir that already holds a database.
|
||||
func withDB(t *testing.T, cfg config.TrivyConfig) config.TrivyConfig {
|
||||
t.Helper()
|
||||
cfg.CacheDB = t.TempDir()
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(cfg.CacheDB, "db"), 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(cfg.CacheDB, "db", "trivy.db"), nil, 0o600))
|
||||
return cfg
|
||||
}
|
||||
|
||||
// fakeTrivy downloads a database on `trivy image` and scans clean otherwise, logging each step.
|
||||
func fakeTrivy(t *testing.T, scanSleep string) (logFile string) {
|
||||
t.Helper()
|
||||
logFile = filepath.Join(t.TempDir(), "log")
|
||||
scannertest.Script(t, "trivy", `
|
||||
if [ "$1" = image ]; then
|
||||
echo update >> '`+logFile+`'
|
||||
mkdir -p "$TRIVY_CACHE_DIR/db" && : > "$TRIVY_CACHE_DIR/db/trivy.db"
|
||||
exit 0
|
||||
fi
|
||||
echo scan-start >> '`+logFile+`'
|
||||
sleep `+scanSleep+`
|
||||
echo scan-end >> '`+logFile+`'
|
||||
echo '{"Results":[]}'`)
|
||||
return logFile
|
||||
}
|
||||
|
||||
func readLog(t *testing.T, logFile string) []string {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(logFile) // #nosec G304 -- test temp file
|
||||
require.NoError(t, err)
|
||||
return strings.Fields(string(data))
|
||||
}
|
||||
|
||||
func TestScansDownloadAMissingDatabaseOnce(t *testing.T) {
|
||||
logFile := fakeTrivy(t, "0")
|
||||
s := New(config.TrivyConfig{CacheDB: t.TempDir()})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for range 4 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
res, err := s.Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
|
||||
if assert.NoError(t, err) {
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
lines := readLog(t, logFile)
|
||||
assert.Equal(t, "update", lines[0])
|
||||
assert.Equal(t, 1, strings.Count(strings.Join(lines, " "), "update"))
|
||||
}
|
||||
|
||||
// Concurrent trivy processes replacing the database under running scans crashed them with SIGBUS.
|
||||
func TestUpdateWaitsForRunningScans(t *testing.T) {
|
||||
logFile := fakeTrivy(t, "0.3")
|
||||
s := New(withDB(t, config.TrivyConfig{}))
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
_, err := s.Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
require.Eventually(t, func() bool {
|
||||
data, _ := os.ReadFile(logFile) // #nosec G304 -- test temp file
|
||||
return strings.Contains(string(data), "scan-start")
|
||||
}, 5*time.Second, 5*time.Millisecond)
|
||||
require.NoError(t, s.UpdateDatabase(context.Background()))
|
||||
<-done
|
||||
|
||||
assert.Equal(t, []string{"scan-start", "scan-end", "update"}, readLog(t, logFile))
|
||||
}
|
||||
|
||||
func TestRefreshDatabaseRunsOnInterval(t *testing.T) {
|
||||
logFile := fakeTrivy(t, "0")
|
||||
stop := make(chan struct{})
|
||||
exited := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
New(config.TrivyConfig{CacheDB: t.TempDir()}).RefreshDatabase(stop, 20*time.Millisecond, true)
|
||||
close(exited)
|
||||
}()
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
data, _ := os.ReadFile(logFile) // #nosec G304 -- test temp file
|
||||
return strings.Count(string(data), "update\n") >= 3
|
||||
}, 5*time.Second, 10*time.Millisecond)
|
||||
close(stop)
|
||||
select {
|
||||
case <-exited:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("refresh loop did not stop")
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,12 @@ const maxExtractBytes int64 = 512 << 20
|
||||
var errTooLarge = errors.New("archive exceeds the extraction size limit")
|
||||
|
||||
// unpackNPM extracts an npm tarball into root/node_modules/<name>, the layout trivy's node-pkg
|
||||
// analyzer reads. It returns root, which the caller must remove.
|
||||
func unpackNPM(archive, name string) (root string, err error) {
|
||||
// analyzer reads. root is a new dir in parent.
|
||||
func unpackNPM(parent, archive, name string) (root string, err error) {
|
||||
if !validPackageName(name) {
|
||||
return "", fmt.Errorf("unsafe package name %q", name)
|
||||
}
|
||||
root, err = os.MkdirTemp("", "trivy-npm-*")
|
||||
root, err = os.MkdirTemp(parent, "trivy-npm-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
+87
-13
@@ -8,13 +8,17 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/dbrefresh"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -22,10 +26,16 @@ import (
|
||||
// ScannerName is the name of this scanner
|
||||
const ScannerName = "trivy"
|
||||
|
||||
// A full download takes about 11s; this bounds a hung one, during which scans wait.
|
||||
const dbUpdateTimeout = 10 * time.Minute
|
||||
|
||||
// Scanner implements the Scanner interface using Trivy
|
||||
type Scanner struct {
|
||||
version scanver.Cache
|
||||
config config.TrivyConfig
|
||||
// Scans hold the read lock, updates the write lock: trivy processes that read the database
|
||||
// while another replaced it crashed with SIGBUS.
|
||||
dbMu sync.RWMutex
|
||||
}
|
||||
|
||||
// TrivyResult represents Trivy JSON output structure
|
||||
@@ -85,14 +95,63 @@ func (s *Scanner) Name() string {
|
||||
return ScannerName
|
||||
}
|
||||
|
||||
// UpdateDatabase updates Trivy's vulnerability database
|
||||
// UpdateDatabase updates Trivy's vulnerability database. It waits for running scans, and
|
||||
// scans wait for it.
|
||||
func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
||||
s.dbMu.Lock()
|
||||
defer s.dbMu.Unlock()
|
||||
return s.download(ctx)
|
||||
}
|
||||
|
||||
// RefreshDatabase updates the database every interval until stop closes. immediate runs
|
||||
// the first update at once; otherwise it waits one interval. interval 0 means 6h.
|
||||
func (s *Scanner) RefreshDatabase(stop <-chan struct{}, interval time.Duration, immediate bool) {
|
||||
dbrefresh.Run(stop, interval, immediate, ScannerName, s.UpdateDatabase)
|
||||
}
|
||||
|
||||
// ensureDatabase downloads the database when the cache has none: a scan never updates it.
|
||||
func (s *Scanner) ensureDatabase(ctx context.Context) error {
|
||||
if s.hasDatabase() {
|
||||
return nil
|
||||
}
|
||||
s.dbMu.Lock()
|
||||
defer s.dbMu.Unlock()
|
||||
if s.hasDatabase() {
|
||||
return nil
|
||||
}
|
||||
return s.download(ctx)
|
||||
}
|
||||
|
||||
// hasDatabase reports whether trivy's cache dir holds a vulnerability database.
|
||||
func (s *Scanner) hasDatabase() bool {
|
||||
dir := s.config.CacheDB
|
||||
if dir == "" {
|
||||
dir = os.Getenv("TRIVY_CACHE_DIR")
|
||||
}
|
||||
if dir == "" {
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
dir = filepath.Join(cache, "trivy")
|
||||
}
|
||||
_, err := os.Stat(filepath.Join(dir, "db", "trivy.db")) // #nosec G703 -- cache dir from config or env
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// download runs the database update. The caller holds the write lock.
|
||||
func (s *Scanner) download(ctx context.Context) error {
|
||||
log.Info().Msg("Updating Trivy vulnerability database")
|
||||
|
||||
cmd := exec.CommandContext(ctx, "trivy", "image", "--download-db-only")
|
||||
if s.config.CacheDB != "" {
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("TRIVY_CACHE_DIR=%s", s.config.CacheDB))
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer wd.Remove()
|
||||
ctx, cancel := context.WithTimeout(ctx, dbUpdateTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "trivy", "image", "--download-db-only")
|
||||
cmd.Env = s.env(wd)
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
@@ -105,6 +164,12 @@ func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
||||
|
||||
// Scan scans a package for vulnerabilities using Trivy
|
||||
func (s *Scanner) Scan(ctx context.Context, registry, packageName, version string, filePath string) (*metadata.ScanResult, error) {
|
||||
if err := s.ensureDatabase(ctx); err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", scanerr.ErrInfrastructure, err)
|
||||
}
|
||||
s.dbMu.RLock()
|
||||
defer s.dbMu.RUnlock()
|
||||
|
||||
// Set timeout
|
||||
if s.config.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
@@ -112,31 +177,31 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
|
||||
scanType := s.determineScanType(registry, filePath)
|
||||
target := filePath
|
||||
if registry == "npm" {
|
||||
// trivy does not unpack archives; the node-pkg analyzer needs an installed tree.
|
||||
root, err := unpackNPM(filePath, packageName)
|
||||
if err != nil {
|
||||
if target, err = unpackNPM(wd.Path(), filePath, packageName); err != nil {
|
||||
return nil, fmt.Errorf("prepare npm package for trivy: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(root) }()
|
||||
target = root
|
||||
}
|
||||
|
||||
args := []string{
|
||||
scanType,
|
||||
"--format", "json",
|
||||
"--quiet",
|
||||
"--skip-db-update", // RefreshDatabase owns updates
|
||||
target,
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
|
||||
|
||||
// Set cache directory if configured
|
||||
if s.config.CacheDB != "" {
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("TRIVY_CACHE_DIR=%s", s.config.CacheDB))
|
||||
}
|
||||
cmd.Env = s.env(wd)
|
||||
|
||||
// Execute scan
|
||||
output, err := cmd.Output()
|
||||
@@ -168,6 +233,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
return s.convertTrivyResult(&trivyResult, registry, packageName, version), nil
|
||||
}
|
||||
|
||||
// env runs trivy in wd, with the configured cache dir.
|
||||
func (s *Scanner) env(wd *workdir.Dir) []string {
|
||||
env := wd.Env(os.Environ())
|
||||
if s.config.CacheDB != "" {
|
||||
env = append(env, "TRIVY_CACHE_DIR="+s.config.CacheDB)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// determineScanType determines the appropriate Trivy scan type
|
||||
func (s *Scanner) determineScanType(registry, filePath string) string {
|
||||
// For now, use filesystem scan for packages
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) {
|
||||
scannertest.Script(t, "trivy", "exec sleep 5")
|
||||
|
||||
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "pypi", "p", "1", "/x")
|
||||
res, err := New(withDB(t, config.TrivyConfig{Timeout: 100 * time.Millisecond})).Scan(context.Background(), "pypi", "p", "1", "/x")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
||||
@@ -76,7 +76,7 @@ echo '{"Results":[]}'`, rec))
|
||||
entry{name: "package/lib/index.js", body: "x"},
|
||||
)
|
||||
|
||||
res, err := New(config.TrivyConfig{}).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive)
|
||||
res, err := New(withDB(t, config.TrivyConfig{})).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
@@ -85,7 +85,7 @@ echo '{"Results":[]}'`, rec))
|
||||
root, err := os.ReadFile(filepath.Join(rec, "root")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
lines := strings.Split(strings.TrimSpace(string(args)), "\n")
|
||||
assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", strings.TrimSpace(string(root))}, lines)
|
||||
assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", "--skip-db-update", strings.TrimSpace(string(root))}, lines)
|
||||
pkg, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{"name":"@scope/pkg"}`, string(pkg))
|
||||
@@ -95,9 +95,9 @@ echo '{"Results":[]}'`, rec))
|
||||
|
||||
func TestNonNPMScansTheFileWithFS(t *testing.T) {
|
||||
argsFile := scannertest.Fake(t, "trivy", "", "", 0)
|
||||
_, err := New(config.TrivyConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
|
||||
_, err := New(withDB(t, config.TrivyConfig{})).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
|
||||
require.Error(t, err) // empty output is not JSON
|
||||
assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "/x/p.whl"}, scannertest.Args(t, argsFile))
|
||||
assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "--skip-db-update", "/x/p.whl"}, scannertest.Args(t, argsFile))
|
||||
}
|
||||
|
||||
func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||
@@ -114,7 +114,7 @@ func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
root, err := unpackNPM(tgz(t, tt.entries...), "pkg")
|
||||
root, err := unpackNPM(t.TempDir(), tgz(t, tt.entries...), "pkg")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, root)
|
||||
})
|
||||
@@ -122,12 +122,11 @@ func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
|
||||
root, err := unpackNPM(tgz(t,
|
||||
root, err := unpackNPM(t.TempDir(), tgz(t,
|
||||
entry{name: "package/real.js", body: "x"},
|
||||
entry{name: "package/l", typeflag: tar.TypeSymlink, link: "real.js"},
|
||||
), "pkg")
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = os.RemoveAll(root) }()
|
||||
_, err = os.Lstat(filepath.Join(root, "node_modules", "pkg", "l"))
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
assert.FileExists(t, filepath.Join(root, "node_modules", "pkg", "real.js"))
|
||||
@@ -136,7 +135,7 @@ func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
|
||||
func TestUnpackRejectsUnsafePackageNames(t *testing.T) {
|
||||
archive := tgz(t, entry{name: "package/package.json", body: "{}"})
|
||||
for _, name := range []string{"", "..", "../x", "/abs", "a/../../b", `a\b`} {
|
||||
_, err := unpackNPM(archive, name)
|
||||
_, err := unpackNPM(t.TempDir(), archive, name)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Package workdir gives each scanner run a private temp dir. The scanner binary gets it as
|
||||
// TMPDIR, so the files it stages there, such as the database download of a trivy killed by
|
||||
// its timeout, are removed with the dir.
|
||||
package workdir
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
prefix = "gohoarder-scan-"
|
||||
// Far past every scanner timeout, so a sweep never takes the dir of a scan still running elsewhere.
|
||||
abandonedAfter = time.Hour
|
||||
)
|
||||
|
||||
var (
|
||||
liveMu sync.Mutex
|
||||
live = map[string]struct{}{}
|
||||
// One sweep at a time; concurrent scans skip it instead of queueing.
|
||||
sweeping sync.Mutex
|
||||
)
|
||||
|
||||
// Dir is the temp dir of one scanner run.
|
||||
type Dir struct {
|
||||
path string
|
||||
}
|
||||
|
||||
// New sweeps abandoned work dirs, then creates one for scanner.
|
||||
func New(scanner string) (*Dir, error) {
|
||||
sweep(time.Now().Add(-abandonedAfter))
|
||||
path, err := os.MkdirTemp("", prefix+scanner+"-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create scan work dir: %w", err)
|
||||
}
|
||||
liveMu.Lock()
|
||||
live[path] = struct{}{}
|
||||
liveMu.Unlock()
|
||||
return &Dir{path: path}, nil
|
||||
}
|
||||
|
||||
// Path returns the work dir.
|
||||
func (d *Dir) Path() string { return d.path }
|
||||
|
||||
// Env returns env with TMPDIR set to the work dir; exec uses the last value of a duplicate key.
|
||||
func (d *Dir) Env(env []string) []string {
|
||||
return append(env, "TMPDIR="+d.path)
|
||||
}
|
||||
|
||||
// Remove deletes the work dir and everything in it. A dir it cannot delete is left to a later sweep.
|
||||
func (d *Dir) Remove() {
|
||||
err := os.RemoveAll(d.path)
|
||||
liveMu.Lock()
|
||||
delete(live, d.path)
|
||||
liveMu.Unlock()
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("path", d.path).Msg("Cannot remove scan work dir")
|
||||
}
|
||||
}
|
||||
|
||||
// sweep removes work dirs last modified before cutoff that no scan in this process uses: those of
|
||||
// a process killed mid-scan, and those Remove could not delete.
|
||||
func sweep(cutoff time.Time) {
|
||||
if !sweeping.TryLock() {
|
||||
return
|
||||
}
|
||||
defer sweeping.Unlock()
|
||||
|
||||
dir := os.TempDir()
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot list dir for abandoned scan work dirs")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() || !strings.HasPrefix(e.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, e.Name())
|
||||
liveMu.Lock()
|
||||
_, inUse := live[path]
|
||||
liveMu.Unlock()
|
||||
if inUse {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil || !info.ModTime().Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
log.Warn().Err(err).Str("path", path).Msg("Cannot remove abandoned scan work dir")
|
||||
continue
|
||||
}
|
||||
log.Info().Str("path", path).Msg("Removed abandoned scan work dir")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package workdir
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func entries(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
list, err := os.ReadDir(dir)
|
||||
require.NoError(t, err)
|
||||
names := make([]string, 0, len(list))
|
||||
for _, e := range list {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestRemoveDeletesWhatTheScannerLeft(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
|
||||
wd, err := New("trivy")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tmp, filepath.Dir(wd.Path()))
|
||||
assert.Equal(t, "TMPDIR="+wd.Path(), wd.Env([]string{"TMPDIR=/tmp"})[1])
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(wd.Path(), "trivy-1", "db"), 0o700))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(wd.Path(), "trivy-1", "db", "trivy.db"), []byte("x"), 0o600))
|
||||
|
||||
wd.Remove()
|
||||
|
||||
assert.Empty(t, entries(t, tmp))
|
||||
}
|
||||
|
||||
func TestSweepRemovesOnlyAbandonedDirs(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
old := time.Now().Add(-2 * abandonedAfter)
|
||||
mk := func(name string, mtime time.Time) {
|
||||
path := filepath.Join(tmp, name)
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(path, "x"), 0o700))
|
||||
require.NoError(t, os.Chtimes(path, mtime, mtime))
|
||||
}
|
||||
mk(prefix+"trivy-1", old)
|
||||
mk(prefix+"npm-audit-2", time.Now())
|
||||
mk("trivy-3", old)
|
||||
live, err := New("grype")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chtimes(live.Path(), old, old))
|
||||
|
||||
sweep(time.Now().Add(-abandonedAfter))
|
||||
|
||||
assert.ElementsMatch(t, []string{prefix + "npm-audit-2", "trivy-3", filepath.Base(live.Path())}, entries(t, tmp))
|
||||
live.Remove()
|
||||
}
|
||||
|
||||
func TestSweepRetriesADirWhoseRemoveFailed(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
wd, err := New("trivy")
|
||||
require.NoError(t, err)
|
||||
locked := filepath.Join(wd.Path(), "locked")
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(locked, "f"), 0o700))
|
||||
require.NoError(t, os.Chmod(locked, 0o500)) // #nosec G302 -- read-only on purpose
|
||||
t.Cleanup(func() { _ = os.Chmod(locked, 0o700) }) // #nosec G302 -- test dir
|
||||
|
||||
wd.Remove()
|
||||
require.NoError(t, os.Chmod(locked, 0o700)) // #nosec G302 -- test dir
|
||||
old := time.Now().Add(-2 * abandonedAfter)
|
||||
require.NoError(t, os.Chtimes(wd.Path(), old, old))
|
||||
sweep(time.Now().Add(-abandonedAfter))
|
||||
|
||||
assert.Empty(t, entries(t, tmp))
|
||||
}
|
||||
|
||||
func TestConcurrentScansLeaveNothing(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
var wg sync.WaitGroup
|
||||
for range 16 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
wd, err := New("npm-audit")
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
assert.NoError(t, os.WriteFile(filepath.Join(wd.Path(), "f"), []byte("x"), 0o600))
|
||||
wd.Remove()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
assert.Empty(t, entries(t, tmp))
|
||||
}
|
||||
Reference in New Issue
Block a user