mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-28 06:46:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7b9917696 | ||
|
|
3143de3a3f | ||
|
|
f0b37ea719 | ||
|
|
7192e4ff3e | ||
|
|
ad4e848e2b | ||
|
|
990a1d3409 | ||
|
|
440279aa50 | ||
|
|
1f31256769 | ||
|
|
4713524778 | ||
|
|
5c9f7e6af3 | ||
|
|
6f604367da | ||
|
|
c98720c02e | ||
|
|
9a44683fbd | ||
|
|
d6edd40d79 | ||
|
|
99c885cd88 | ||
|
|
c022824d2b | ||
|
|
5420480ef8 | ||
|
|
bde9eebf3d | ||
|
|
f65c0cc1f3 |
@@ -72,6 +72,7 @@ tests/fixtures/temp/
|
||||
# Markdown files (except README.md)
|
||||
*.md
|
||||
!README.md
|
||||
!lean4/FINDINGS.md
|
||||
|
||||
/gohoarder
|
||||
*.log
|
||||
@@ -83,3 +84,4 @@ data/storage
|
||||
|
||||
# Local worktrees
|
||||
.worktrees/
|
||||
lean4/.lake
|
||||
|
||||
@@ -233,7 +233,9 @@ security:
|
||||
enabled: true
|
||||
|
||||
cache:
|
||||
default_ttl: 86400 # 24 hours in seconds
|
||||
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
|
||||
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
|
||||
cleanup_interval: 1h
|
||||
|
||||
logging:
|
||||
level: "info" # debug, info, warn, error
|
||||
@@ -245,6 +247,15 @@ upstream:
|
||||
go: "https://proxy.golang.org"
|
||||
```
|
||||
|
||||
#### Cache cleanup
|
||||
|
||||
Every `cleanup_interval` the cleanup run removes:
|
||||
|
||||
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
|
||||
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl`. They refresh on the next request.
|
||||
|
||||
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
All configuration values can be overridden with environment variables:
|
||||
|
||||
+2
-1
@@ -89,8 +89,9 @@ metadata:
|
||||
log_level: "warn" # GORM log level: silent, error, warn, info
|
||||
|
||||
cache:
|
||||
default_ttl: "168h" # 7 days
|
||||
default_ttl: "168h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
cleanup_interval: "1h"
|
||||
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
max_size_bytes: 536870912000 # 500GB
|
||||
per_project_quota: 53687091200 # 50GB
|
||||
ttl_overrides:
|
||||
|
||||
@@ -5,3 +5,6 @@ VITE_BACKEND_URL=http://localhost:8080
|
||||
# Frontend dev server port
|
||||
# The Vite development server will run on this port
|
||||
VITE_PORT=5173
|
||||
|
||||
# Origin sent on the dev WebSocket proxy, for a backend with an allowed-origins list
|
||||
# VITE_WS_ORIGIN=https://gohoarder.example.com
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<link rel="icon" href="data:," />
|
||||
<title>GoHoarder dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Generated
+144
-87
@@ -24,19 +24,19 @@ importers:
|
||||
version: 7.3.1
|
||||
'@perfect-design/ui':
|
||||
specifier: 0.3.10
|
||||
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))
|
||||
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))
|
||||
axios:
|
||||
specifier: ^1.20.0
|
||||
version: 1.21.1
|
||||
version: 1.21.1([email protected]([email protected]))([email protected])
|
||||
pinia:
|
||||
specifier: ^4.0.0
|
||||
version: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
|
||||
version: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
|
||||
vue:
|
||||
specifier: ^3.5.26
|
||||
version: 3.5.45([email protected])
|
||||
version: 3.5.46([email protected])
|
||||
vue-router:
|
||||
specifier: ^5.3.1
|
||||
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected]))
|
||||
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected]))
|
||||
devDependencies:
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.3.3
|
||||
@@ -46,13 +46,13 @@ importers:
|
||||
version: 7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
|
||||
'@testing-library/vue':
|
||||
specifier: ^8.1.0
|
||||
version: 8.1.0(@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))
|
||||
version: 8.1.0(@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))
|
||||
'@vitejs/plugin-vue':
|
||||
specifier: ^6.0.3
|
||||
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]5([email protected]))
|
||||
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]6([email protected]))
|
||||
'@vue/test-utils':
|
||||
specifier: ^2.4.6
|
||||
version: 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
|
||||
version: 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
|
||||
jsdom:
|
||||
specifier: ^31.0.0
|
||||
version: 31.0.1
|
||||
@@ -654,18 +654,30 @@ packages:
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-6u4vXBlIBAC1wMplIZgpyPn7uh/s4Bf6F5bMzvLv+EdJ0aHs/+4B7Ygv864EStQSjRbsRzTko/kUG1A1IejQ3A==}
|
||||
|
||||
@@ -678,17 +690,17 @@ packages:
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==}
|
||||
|
||||
'@vue/[email protected]5':
|
||||
resolution: {integrity: sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==}
|
||||
'@vue/[email protected]6':
|
||||
resolution: {integrity: sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==}
|
||||
|
||||
'@vue/[email protected]5':
|
||||
resolution: {integrity: sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==}
|
||||
'@vue/[email protected]6':
|
||||
resolution: {integrity: sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==}
|
||||
|
||||
'@vue/[email protected]5':
|
||||
resolution: {integrity: sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==}
|
||||
'@vue/[email protected]6':
|
||||
resolution: {integrity: sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==}
|
||||
|
||||
'@vue/[email protected]5':
|
||||
resolution: {integrity: sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==}
|
||||
'@vue/[email protected]6':
|
||||
resolution: {integrity: sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==}
|
||||
@@ -696,6 +708,9 @@ packages:
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==}
|
||||
|
||||
'@vue/[email protected]':
|
||||
resolution: {integrity: sha512-kTB6s2p34cA/xXSpt17G0enU9A3F3pdm+o5GZgE3WGXXXpXJ5SVBsRhgCJNCc+ekGAzY0T7Hjyo5yEfwencBlg==}
|
||||
peerDependencies:
|
||||
@@ -855,8 +870,8 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
|
||||
|
||||
[email protected].3:
|
||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||
[email protected].4:
|
||||
resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==}
|
||||
@@ -1476,6 +1491,10 @@ packages:
|
||||
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==}
|
||||
engines: {node: '>=6.0.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
|
||||
|
||||
@@ -1710,8 +1729,8 @@ packages:
|
||||
peerDependencies:
|
||||
typescript: '>=5.0.0'
|
||||
|
||||
[email protected]5:
|
||||
resolution: {integrity: sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==}
|
||||
[email protected]6:
|
||||
resolution: {integrity: sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==}
|
||||
peerDependencies:
|
||||
typescript: '*'
|
||||
peerDependenciesMeta:
|
||||
@@ -1901,11 +1920,11 @@ snapshots:
|
||||
|
||||
'@floating-ui/[email protected]': {}
|
||||
|
||||
'@floating-ui/[email protected]([email protected]5([email protected]))':
|
||||
'@floating-ui/[email protected]([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
'@floating-ui/dom': 1.8.0
|
||||
'@floating-ui/utils': 0.2.12
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
'@fontsource/[email protected]': {}
|
||||
|
||||
@@ -1948,13 +1967,13 @@ snapshots:
|
||||
|
||||
'@oxc-project/[email protected]': {}
|
||||
|
||||
'@perfect-design/[email protected]([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))':
|
||||
'@perfect-design/[email protected]([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
|
||||
reka-ui: 2.11.0([email protected]5([email protected]))
|
||||
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
|
||||
reka-ui: 2.11.0([email protected]6([email protected]))
|
||||
tailwind-merge: 3.7.1
|
||||
tailwindcss: 4.3.5
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
optional: true
|
||||
@@ -2077,10 +2096,10 @@ snapshots:
|
||||
|
||||
'@tanstack/[email protected]': {}
|
||||
|
||||
'@tanstack/[email protected]([email protected]5([email protected]))':
|
||||
'@tanstack/[email protected]([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
'@tanstack/virtual-core': 3.13.14
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
'@testing-library/[email protected]':
|
||||
dependencies:
|
||||
@@ -2116,12 +2135,12 @@ snapshots:
|
||||
optionalDependencies:
|
||||
vitest: 5.1.1([email protected])([email protected]([email protected])([email protected]))
|
||||
|
||||
'@testing-library/[email protected](@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))':
|
||||
'@testing-library/[email protected](@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.28.4
|
||||
'@testing-library/dom': 9.3.4
|
||||
'@vue/test-utils': 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
|
||||
vue: 3.5.45([email protected])
|
||||
'@vue/test-utils': 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
|
||||
vue: 3.5.46([email protected])
|
||||
optionalDependencies:
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
transitivePeerDependencies:
|
||||
@@ -2141,11 +2160,11 @@ snapshots:
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]5([email protected]))':
|
||||
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
'@rolldown/pluginutils': 1.0.1
|
||||
vite: 8.3.8([email protected])([email protected])
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
'@vitest/[email protected]([email protected]([email protected])([email protected]))':
|
||||
dependencies:
|
||||
@@ -2182,7 +2201,7 @@ snapshots:
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
'@vue-macros/[email protected]([email protected]5([email protected]))':
|
||||
'@vue-macros/[email protected]([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
ast-kit: 2.2.0
|
||||
@@ -2190,7 +2209,7 @@ snapshots:
|
||||
magic-string-ast: 1.0.3
|
||||
unplugin-utils: 0.3.2
|
||||
optionalDependencies:
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
@@ -2208,6 +2227,14 @@ snapshots:
|
||||
estree-walker: 2.0.2
|
||||
source-map-js: 1.2.2
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.13
|
||||
'@vue/shared': 3.5.46
|
||||
entities: 7.0.1
|
||||
estree-walker: 2.0.2
|
||||
source-map-js: 1.2.4
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@vue/compiler-core': 3.5.44
|
||||
@@ -2218,6 +2245,11 @@ snapshots:
|
||||
'@vue/compiler-core': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@vue/compiler-core': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.13
|
||||
@@ -2230,11 +2262,28 @@ snapshots:
|
||||
postcss: 8.5.32
|
||||
source-map-js: 1.2.2
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.13
|
||||
'@vue/compiler-core': 3.5.46
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
'@vue/compiler-ssr': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
estree-walker: 2.0.2
|
||||
magic-string: 0.30.21
|
||||
postcss: 8.5.32
|
||||
source-map-js: 1.2.4
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/[email protected]':
|
||||
dependencies:
|
||||
'@vue/devtools-kit': 8.2.1
|
||||
@@ -2258,61 +2307,63 @@ snapshots:
|
||||
path-browserify: 1.0.1
|
||||
picomatch: 4.0.7
|
||||
|
||||
'@vue/[email protected]5':
|
||||
'@vue/[email protected]6':
|
||||
dependencies:
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/[email protected]5':
|
||||
'@vue/[email protected]6':
|
||||
dependencies:
|
||||
'@vue/reactivity': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/reactivity': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/[email protected]5':
|
||||
'@vue/[email protected]6':
|
||||
dependencies:
|
||||
'@vue/reactivity': 3.5.45
|
||||
'@vue/runtime-core': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
csstype: 3.2.3
|
||||
'@vue/reactivity': 3.5.46
|
||||
'@vue/runtime-core': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
csstype: 3.2.4
|
||||
|
||||
'@vue/[email protected]5':
|
||||
'@vue/[email protected]6':
|
||||
dependencies:
|
||||
'@vue/compiler-ssr': 3.5.45
|
||||
'@vue/runtime-dom': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/compiler-ssr': 3.5.46
|
||||
'@vue/runtime-dom': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/[email protected]': {}
|
||||
|
||||
'@vue/[email protected]': {}
|
||||
|
||||
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
|
||||
'@vue/[email protected]': {}
|
||||
|
||||
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.45
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
js-beautify: 2.0.3
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
vue-component-type-helpers: 3.3.12
|
||||
optionalDependencies:
|
||||
'@vue/server-renderer': 3.5.45
|
||||
'@vue/server-renderer': 3.5.46
|
||||
|
||||
'@vueuse/[email protected]([email protected]5([email protected]))':
|
||||
'@vueuse/[email protected]([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
'@types/web-bluetooth': 0.0.21
|
||||
'@vueuse/metadata': 14.4.0
|
||||
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
|
||||
vue: 3.5.45([email protected])
|
||||
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
'@vueuse/[email protected]': {}
|
||||
|
||||
'@vueuse/[email protected]([email protected]5([email protected]))':
|
||||
'@vueuse/[email protected]([email protected]6([email protected]))':
|
||||
dependencies:
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
debug: 4.4.3([email protected])
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -2368,11 +2419,11 @@ snapshots:
|
||||
dependencies:
|
||||
possible-typed-array-names: 1.1.0
|
||||
|
||||
[email protected]:
|
||||
[email protected]([email protected]([email protected]))([email protected]):
|
||||
dependencies:
|
||||
follow-redirects: 1.16.3
|
||||
follow-redirects: 1.16.3([email protected]([email protected]))
|
||||
form-data: 4.0.6
|
||||
https-proxy-agent: 5.0.1
|
||||
https-proxy-agent: 5.0.1([email protected])
|
||||
proxy-from-env: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
- debug
|
||||
@@ -2445,7 +2496,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected].3: {}
|
||||
[email protected].4: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2454,9 +2505,11 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- '@noble/hashes'
|
||||
|
||||
[email protected]:
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
optionalDependencies:
|
||||
supports-color: 7.2.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -2600,7 +2653,9 @@ snapshots:
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.7
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]([email protected]([email protected])):
|
||||
optionalDependencies:
|
||||
debug: 4.4.3([email protected])
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2675,10 +2730,10 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- '@noble/hashes'
|
||||
|
||||
[email protected]:
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
agent-base: 6.0.2
|
||||
debug: 4.4.3
|
||||
agent-base: 6.0.2([email protected])
|
||||
debug: 4.4.3([email protected])
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -2968,11 +3023,11 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected](@vue/[email protected])([email protected])([email protected]5([email protected])):
|
||||
[email protected](@vue/[email protected])([email protected])([email protected]6([email protected])):
|
||||
dependencies:
|
||||
'@vue/devtools-api': 8.2.1
|
||||
nostics: 1.3.0
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
@@ -3030,18 +3085,18 @@ snapshots:
|
||||
gopd: 1.2.0
|
||||
set-function-name: 2.0.2
|
||||
|
||||
[email protected]([email protected]5([email protected])):
|
||||
[email protected]([email protected]6([email protected])):
|
||||
dependencies:
|
||||
'@floating-ui/vue': 2.0.1([email protected]5([email protected]))
|
||||
'@floating-ui/vue': 2.0.1([email protected]6([email protected]))
|
||||
'@internationalized/date': 3.10.1
|
||||
'@internationalized/number': 3.6.5
|
||||
'@tanstack/vue-virtual': 3.13.14([email protected]5([email protected]))
|
||||
'@vueuse/core': 14.4.0([email protected]5([email protected]))
|
||||
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
|
||||
'@tanstack/vue-virtual': 3.13.14([email protected]6([email protected]))
|
||||
'@vueuse/core': 14.4.0([email protected]6([email protected]))
|
||||
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
|
||||
aria-hidden: 1.2.6
|
||||
defu: 6.1.7
|
||||
ohash: 2.0.11
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -3124,6 +3179,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
@@ -3240,9 +3297,9 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected])):
|
||||
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected])):
|
||||
dependencies:
|
||||
'@vue-macros/common': 3.1.4([email protected]5([email protected]))
|
||||
'@vue-macros/common': 3.1.4([email protected]6([email protected]))
|
||||
'@vue/devtools-api': 8.2.1
|
||||
ast-walker-scope: 0.10.0
|
||||
chokidar: 6.0.0
|
||||
@@ -3258,10 +3315,10 @@ snapshots:
|
||||
tinyglobby: 0.2.17
|
||||
unplugin: 3.7.0([email protected])([email protected])([email protected]([email protected])([email protected]))
|
||||
unplugin-utils: 0.3.2
|
||||
vue: 3.5.45([email protected])
|
||||
vue: 3.5.46([email protected])
|
||||
optionalDependencies:
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
|
||||
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
|
||||
vite: 8.3.8([email protected])([email protected])
|
||||
transitivePeerDependencies:
|
||||
- '@farmfe/core'
|
||||
@@ -3280,13 +3337,13 @@ snapshots:
|
||||
'@vue/language-core': 3.3.14
|
||||
typescript: 6.0.3
|
||||
|
||||
[email protected]5([email protected]):
|
||||
[email protected]6([email protected]):
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.45
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
'@vue/runtime-dom': 3.5.45
|
||||
'@vue/server-renderer': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
'@vue/compiler-sfc': 3.5.46
|
||||
'@vue/runtime-dom': 3.5.46
|
||||
'@vue/server-renderer': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
:hint="
|
||||
bypassForm.type === 'cve'
|
||||
? 'Enter the CVE ID, for example CVE-2021-23337.'
|
||||
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions.'
|
||||
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
|
||||
"
|
||||
required
|
||||
>
|
||||
@@ -137,6 +137,24 @@
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog v-model:open="showKeyDialog">
|
||||
<DialogContent size="sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Admin API key</DialogTitle>
|
||||
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="flex flex-col gap-4" @submit.prevent="submitApiKey">
|
||||
<Field label="API key" required>
|
||||
<Input v-model="keyInput" type="password" autocomplete="off" />
|
||||
</Field>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="showKeyDialog = false">Cancel</Button>
|
||||
<Button type="submit" :disabled="keyInput.trim() === ''">Continue</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="showDeleteModal"
|
||||
title="Delete bypass?"
|
||||
@@ -222,6 +240,8 @@ const bypassForm = ref({ ...EMPTY_FORM })
|
||||
|
||||
// Get API key from localStorage or prompt user
|
||||
const apiKey = ref<string>('')
|
||||
const keyInput = ref('')
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
const filteredBypasses = computed(() => {
|
||||
let filtered = bypasses.value
|
||||
@@ -264,16 +284,23 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
function promptForApiKey() {
|
||||
const key = prompt('Enter your admin API key:')
|
||||
if (key) {
|
||||
apiKey.value = key
|
||||
localStorage.setItem('admin_api_key', key)
|
||||
fetchBypasses()
|
||||
} else {
|
||||
error.value = 'Admin API key required to manage bypasses'
|
||||
}
|
||||
keyInput.value = ''
|
||||
showKeyDialog.value = true
|
||||
}
|
||||
|
||||
function submitApiKey() {
|
||||
const key = keyInput.value.trim()
|
||||
if (!key) return
|
||||
apiKey.value = key
|
||||
localStorage.setItem('admin_api_key', key)
|
||||
showKeyDialog.value = false
|
||||
fetchBypasses()
|
||||
}
|
||||
|
||||
watch(showKeyDialog, (open) => {
|
||||
if (!open && !apiKey.value) error.value = 'Admin API key required to manage bypasses'
|
||||
})
|
||||
|
||||
async function fetchBypasses() {
|
||||
if (!apiKey.value) {
|
||||
promptForApiKey()
|
||||
|
||||
@@ -127,7 +127,7 @@ import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import {
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
@@ -190,7 +190,8 @@ function labelForEvent(type: EventType): string {
|
||||
function describeEvent(evt: RealtimeEvent): string {
|
||||
const p = evt.payload
|
||||
const name = typeof p.name === 'string' ? p.name : ''
|
||||
const version = typeof p.version === 'string' ? `@${p.version}` : ''
|
||||
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
|
||||
const version = typeof shown === 'string' ? `@${shown}` : ''
|
||||
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
|
||||
if (evt.type === 'stats_update') return ''
|
||||
if (name) return `${registry}${name}${version}`
|
||||
@@ -250,7 +251,7 @@ const chartLabels = computed(() => chartData.value.map((_, index) => getChartLab
|
||||
|
||||
const packageColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', rowHeader: true },
|
||||
{ key: 'version', header: 'Version' },
|
||||
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'registry', header: 'Registry' },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<template #description>
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline">{{ registry }}</Badge>
|
||||
<Badge variant="outline" class="font-mono">v{{ version }}</Badge>
|
||||
<Badge variant="outline" class="font-mono">{{ withVersionPrefix(shownVersion) }}</Badge>
|
||||
</span>
|
||||
</template>
|
||||
</PageHeader>
|
||||
@@ -184,7 +184,7 @@ import {
|
||||
TableRow,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
@@ -201,6 +201,7 @@ const packageName = computed(() => {
|
||||
return nameParam as string
|
||||
})
|
||||
const version = computed(() => route.params.version as string)
|
||||
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
|
||||
|
||||
interface BypassInfo {
|
||||
id: string
|
||||
@@ -221,6 +222,7 @@ interface Vulnerability {
|
||||
}
|
||||
|
||||
interface VulnerabilityResponse {
|
||||
package?: { release_version?: string }
|
||||
scanned: boolean
|
||||
scanner: string
|
||||
scanned_at: string
|
||||
|
||||
@@ -47,8 +47,9 @@
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="2">
|
||||
<span class="flex w-full min-w-0 items-center justify-between gap-4">
|
||||
<span class="min-w-0 text-start">
|
||||
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
|
||||
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<span class="w-full min-w-0 text-start sm:w-auto">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
@@ -115,6 +116,7 @@
|
||||
:page="currentPage"
|
||||
:total="allGroupedPackages.length"
|
||||
:page-size="itemsPerPage"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -207,4 +207,46 @@ describe('Stats.vue', () => {
|
||||
expect(wrapper.findAll('tbody th')).toHaveLength(0)
|
||||
expect(wrapper.text()).toContain('No registries reported')
|
||||
})
|
||||
|
||||
describe('idle eviction note', () => {
|
||||
const baseStats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
|
||||
async function render(idleTtl?: number) {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
|
||||
await wrapper.vm.$nextTick()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
it.each([
|
||||
[604800, 'Cached items not requested for 7 days are removed.'],
|
||||
[86400, 'Cached items not requested for 1 day are removed.'],
|
||||
[129600, 'Cached items not requested for 36 hours are removed.'],
|
||||
[5400, 'Cached items not requested for 90 minutes are removed.'],
|
||||
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
|
||||
const wrapper = await render(seconds)
|
||||
expect(wrapper.text()).toContain(sentence)
|
||||
})
|
||||
|
||||
it('hides the note when idle eviction is off', async () => {
|
||||
const wrapper = await render(0)
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
|
||||
it('hides the note when the API sends no idle_ttl', async () => {
|
||||
const wrapper = await render()
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<Alert v-if="idleTtl > 0" variant="info">
|
||||
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Overall statistics</CardTitle>
|
||||
@@ -91,6 +95,8 @@ import { storeToRefs } from 'pinia'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
@@ -103,7 +109,7 @@ import {
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
@@ -162,6 +168,8 @@ const registries = computed(() => {
|
||||
}))
|
||||
})
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
|
||||
|
||||
const storagePercentage = computed(() => {
|
||||
const totalSize = stats.value?.total_size || 0
|
||||
const maxSize = stats.value?.max_cache_size || 1
|
||||
|
||||
@@ -140,6 +140,31 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(document.body.querySelector('textarea')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
|
||||
localStorage.clear()
|
||||
const prompt = vi.spyOn(window, 'prompt')
|
||||
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(prompt).not.toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('Enter your admin API key to manage bypasses.')
|
||||
|
||||
const input = document.body.querySelector<HTMLInputElement>('input[type="password"]')
|
||||
expect(input).not.toBeNull()
|
||||
input!.value = 'secret-key'
|
||||
input!.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await flushPromises()
|
||||
document.body.querySelector<HTMLFormElement>('input[type="password"]')!.form!.requestSubmit()
|
||||
await flushPromises()
|
||||
|
||||
expect(localStorage.getItem('admin_api_key')).toBe('secret-key')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/api/admin/bypasses'),
|
||||
expect.objectContaining({ headers: { Authorization: 'Bearer secret-key' } }),
|
||||
)
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
})
|
||||
|
||||
it('Stats renders totals, the storage tile and the registry table', async () => {
|
||||
const { wrapper, problems } = await smoke(Stats, '/stats')
|
||||
expect(problems).toEqual([])
|
||||
@@ -186,3 +211,95 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PyPI rows show the release version, not the file name', () => {
|
||||
const FILE = 'six-1.17.0-py2.py3-none-any.whl'
|
||||
const SIX = {
|
||||
id: 'pypi-six',
|
||||
registry: 'pypi',
|
||||
name: 'six',
|
||||
version: FILE,
|
||||
release_version: '1.17.0',
|
||||
size: 1,
|
||||
cached_at: '2026-02-01T10:00:00Z',
|
||||
last_accessed: '2026-02-01T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
|
||||
total: 1,
|
||||
scannedAt: '2026-02-01T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.endsWith('/vulnerabilities')) {
|
||||
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
|
||||
}
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
|
||||
return respond(url) as never
|
||||
})
|
||||
})
|
||||
|
||||
it('Dashboard recent packages', async () => {
|
||||
const { wrapper } = await smoke(Dashboard, '/')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('Dashboard activity feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
|
||||
const { wrapper, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
|
||||
expect(feed).toContain('[email protected]')
|
||||
expect(feed).not.toContain('whl')
|
||||
})
|
||||
|
||||
it('VulnerablePackages version column', async () => {
|
||||
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
await flushPromises()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('PackageDetails header badge', async () => {
|
||||
const { wrapper } = await smoke(PackageDetails, `/package/pypi/six/${FILE}`)
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push(`/package/pypi/six/${FILE}`)
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('PackageDetails falls back to the route version without a release version', async () => {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
|
||||
const { wrapper } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.3.0')
|
||||
})
|
||||
|
||||
it('bypass form tells PyPI users to use the release version', async () => {
|
||||
const { wrapper } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
await wrapper.findAll('button').find((b) => b.text() === 'Create bypass')!.trigger('click')
|
||||
await flushPromises()
|
||||
const pkg = Array.from(document.body.querySelectorAll<HTMLElement>('button, [role="radio"]')).find((e) => e.textContent?.trim() === 'Package bypass')
|
||||
pkg!.click()
|
||||
await flushPromises()
|
||||
expect(document.body.textContent).toContain('pypi/[email protected]')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatDuration } from './format'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it.each([
|
||||
[604800, '7 days'],
|
||||
[86400, '1 day'],
|
||||
[129600, '36 hours'],
|
||||
[3600, '1 hour'],
|
||||
[5400, '90 minutes'],
|
||||
[60, '1 minute'],
|
||||
])('formats %i seconds as %s', (seconds, expected) => {
|
||||
expect(formatDuration(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,21 @@ export function formatBytes(bytes: number): string {
|
||||
return Math.round((bytes / Math.pow(BYTES_PER_UNIT, i)) * 100) / 100 + ' ' + BYTE_UNITS[i]
|
||||
}
|
||||
|
||||
const SECONDS_PER_DAY = 86400
|
||||
const SECONDS_PER_HOUR = 3600
|
||||
const SECONDS_PER_MINUTE = 60
|
||||
|
||||
function plural(n: number, unit: string): string {
|
||||
return `${n} ${unit}${n === 1 ? '' : 's'}`
|
||||
}
|
||||
|
||||
/** Whole days, hours or minutes, using the largest unit that divides the span evenly. */
|
||||
export function formatDuration(seconds: number): string {
|
||||
if (seconds % SECONDS_PER_DAY === 0) return plural(seconds / SECONDS_PER_DAY, 'day')
|
||||
if (seconds % SECONDS_PER_HOUR === 0) return plural(seconds / SECONDS_PER_HOUR, 'hour')
|
||||
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
|
||||
}
|
||||
|
||||
export function formatDate(date: string): string {
|
||||
if (!date) return 'N/A'
|
||||
const parsed = new Date(date)
|
||||
|
||||
@@ -40,6 +40,8 @@ export interface Stats {
|
||||
scanned_packages: number
|
||||
vulnerable_packages: number
|
||||
blocked_packages: number
|
||||
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
|
||||
idle_ttl?: number
|
||||
}
|
||||
|
||||
export const usePackageStore = defineStore('packages', () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { themeBootScript } from '@perfect-design/ui/stores/theme-boot'
|
||||
|
||||
// Get backend URL from environment or use default
|
||||
const BACKEND_URL = process.env.VITE_BACKEND_URL || 'http://localhost:8080'
|
||||
const WS_ORIGIN = process.env.VITE_WS_ORIGIN
|
||||
const FRONTEND_PORT = parseInt(process.env.VITE_PORT || '5173')
|
||||
|
||||
// Applies the saved colour mode before first paint so a dark system never flashes light.
|
||||
@@ -33,6 +34,8 @@ export default defineConfig({
|
||||
target: BACKEND_URL.replace('http', 'ws'),
|
||||
ws: true,
|
||||
changeOrigin: true,
|
||||
// A backend with an origin allowlist refuses the dev server origin; set this to an allowed one.
|
||||
...(WS_ORIGIN ? { headers: { Origin: WS_ORIGIN } } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -15,6 +15,7 @@ require (
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/lib/pq v1.12.3
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
github.com/prometheus/client_model v0.6.3
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/viper v1.21.0
|
||||
@@ -87,7 +88,7 @@ require (
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/klauspost/compress v1.20.5 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 // indirect
|
||||
github.com/magiconair/properties v1.18.13 // indirect
|
||||
github.com/mattn/go-colorable v0.1.16 // indirect
|
||||
@@ -110,7 +111,6 @@ require (
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/philhofer/fwd v1.2.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.74.0 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.12.0 // indirect
|
||||
@@ -127,7 +127,7 @@ require (
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.79.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
|
||||
@@ -149,8 +149,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
|
||||
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -218,8 +218,8 @@ github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/n
|
||||
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
|
||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
|
||||
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
@@ -278,8 +278,8 @@ github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcY
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
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/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE=
|
||||
go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
|
||||
@@ -73,6 +73,7 @@ data:
|
||||
cache:
|
||||
default_ttl: {{ .Values.cache.defaultTTL | quote }}
|
||||
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
|
||||
idle_ttl: {{ .Values.cache.idleTTL | quote }}
|
||||
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
|
||||
per_project_quota: {{ .Values.cache.perProjectQuota }}
|
||||
ttl_overrides:
|
||||
|
||||
@@ -377,6 +377,7 @@ migration:
|
||||
cache:
|
||||
defaultTTL: "168h" # 7 days
|
||||
cleanupInterval: "1h"
|
||||
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
maxSizeBytes: 536870912000 # 500GB
|
||||
perProjectQuota: 53687091200 # 50GB
|
||||
ttlOverrides:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.lake/
|
||||
@@ -0,0 +1,72 @@
|
||||
# Lean audit findings
|
||||
|
||||
Audit of GoHoarder at c98720c (v0.1.303) with Lean 4 + Mathlib v4.36.0. Models live in
|
||||
`lean4/Gohoarder/*.lean`; each cites the Go files it models. Statements are "proved about the model".
|
||||
A Lean counterexample is never the evidence alone: every fixed row has a Go test that failed first.
|
||||
|
||||
Build: `cd lean4 && lake exe cache get && lake build && lake env lean scripts/Axioms.lean`.
|
||||
Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
|
||||
## Fixed
|
||||
|
||||
| id | area | claim | class | severity | evidence (Lean / Go test) | fix commit |
|
||||
|----|------|-------|-------|----------|---------------------------|------------|
|
||||
| GH-01 | PyPI fetch | the file fetched from `original_url` is the file the cache key names | security, CWE-345 | high | `Access.old_guard_allows_key_poisoning`, `fixed_guard_binds_key` / `TestHandlePackageFile_OriginalURLFilenameBound` | 5c9f7e6 |
|
||||
| GH-02 | scan decision | a bypassed CVE never blocks, under any `block_on_severity` | correctness (over-block) | low | `Security.old_low_ignores_bypass`, `fully_bypassed_never_blocks` / `TestCheckVulnerabilities_BypassedCVENeverBlocks` | 4713524 |
|
||||
| GH-03 | PyPI scan | scanners are asked about the release version, not the file name | security, CWE-693 | high when a block policy is set | `Security.scan_asks_release_version`, `file_name_is_not_release_version` / `TestScanAsksScannersForReleaseVersion` | 3143de3 |
|
||||
| GH-04 | scan gate | an npm or PyPI package named `*.info` or `*.mod` is scanned | security, CWE-693 | medium | `Cache.npm_named_like_go_metadata_is_scanned`, `old_exempted_npm_package` / `TestCacheHitScansPackagesNamedLikeGoMetadata`, `TestIsMetadataEntry` | f0b37ea |
|
||||
| GH-05 | storage quota | `used` equals bytes on disk after an overwrite | correctness | low | `Cache.put_keeps_usage_exact`, `old_put_inflates_usage` / `TestPutOverwriteKeepsUsageExact`, `TestPutOverwriteWithinQuota` | 1f31256 |
|
||||
| GH-06 | LRU eviction | eviction terminates; an overlapping store waits instead of failing | correctness | medium | `Cache.old_evict_is_stuck`, `fixed_evict_measure_falls` / `TestEvictTerminatesWhenDeletesFail`, `TestEvictWaitsForRunningEviction` | 440279a |
|
||||
| GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 |
|
||||
| GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 |
|
||||
| GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
- **GH-01.** A client requests `/pypi/<victim>/<victim-file>?original_url=https://files.pythonhosted.org/.../<attacker-file>`.
|
||||
The host is on the allowlist, the key is `pypi/<victim>/<victim-file>`, and an uncached key stores the attacker's
|
||||
file. Every later client gets it; OSV judges the victim's name and version. The attacker publishes the file on PyPI
|
||||
and needs no credentials. Reach: any network client of `/pypi`, unauthenticated when `auth.enabled` is false (production).
|
||||
- **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name
|
||||
returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong
|
||||
scan results rather than serving blocked packages; any deployment with a block policy served such packages.
|
||||
- **GH-04.** The publisher of an npm or PyPI package named `x.info` skipped the scan and the block policy. Reach: any package
|
||||
publisher; needs a block policy to matter.
|
||||
|
||||
## Not fixed
|
||||
|
||||
| id | area | claim | verdict | why |
|
||||
|----|------|-------|---------|-----|
|
||||
| GH-10 | key path | `keyToPath` rewrites `..` instead of rejecting; distinct keys share a path | hardening, unreachable | `Keys.keyToPath_not_injective`. A probe through the full app showed the HTTP layer resolves literal `..` and answers 404 to encoded slashes (`/npm/lodash/-/lodash-1.0.0/../../x.tgz` reached upstream as `/lodash/-/lodash-x.tgz`). No key with `..` reaches storage. |
|
||||
| GH-11 | cache hit | the stored SHA-256 is not re-verified on read | by-design | `Put` verifies the stream it just hashed; no doc promises read-side integrity. A check reads up to 2 GB per hit. Disk corruption is outside the proxy's threat model. |
|
||||
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
|
||||
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
|
||||
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. |
|
||||
| GH-15 | release age | a cached packument or index hides new or yanked entries for up to the TTL | by-design | Quoted intent, `pkg/cache/cache.go` store: "TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed based on upstream Cache-Control". Passthrough proved: `Release.rewrite_preserves_upload_time`, `stale_hides_only_gated` (needs TTL <= gate; production 24h <= 72h holds, the compiled default 168h does not, and then the proxy is stricter than the gate). |
|
||||
| GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. |
|
||||
| GH-17 | auth off | with `auth.enabled: false` (production) `DELETE /api/packages/*` is unauthenticated, and `Access-Control-Allow-Origin: *` lets a browser page issue it | by-design, product decision | Quoted intent, `pkg/app/app.go`: "routes are mounted bare to preserve backward-compatible public access". Impact is cache eviction only. Enabling auth is a configuration change the operator owns. |
|
||||
| GH-18 | api keys | `ValidateAPIKey` bcrypt-compares every stored key per request | hardening, CWE-400 | N keys cost N bcrypt checks per bad key. A key-id prefix needs an API change. Zero keys in production. |
|
||||
| GH-19 | SSRF | `network.Client` follows redirects without re-checking the allowlist | hardening | `Access.redirect_escapes_allowlist`. No allowed host redirects (pypi.org, files.pythonhosted.org); a private index host is operator-trusted. |
|
||||
| GH-20 | stats, sqlite | `INSERT OR REPLACE` has no unique index on SQLite, so every pass duplicates registry rows | correctness, SQLite only | Seen in a row dump (three NULL-package hourly rows for one bucket after three passes). Production is PostgreSQL, where `statsUpsertIndexes` exist. Needs a dedupe migration; left open. |
|
||||
| GH-21 | scan retry | a retry on S3 or SMB storage rescans a temp file already removed | suspected, unconfirmed | `cache.go` store removes `tempPath` after the first scan. Production is filesystem. No test written. |
|
||||
|
||||
### Decision: `fail_closed: false` with recurring infrastructure errors
|
||||
|
||||
Served: a package with no scan row while a scan is in flight, and a package whose every scanner failed on infrastructure
|
||||
(`Security.unscanned_served_iff`, `infra_error_served_forever`). Retries: at most 6 at 5 minute spacing, 7 scans, 30
|
||||
minutes (`retry_terminates`, `retry_window_minutes`); after that the error row stays and the package stays served until
|
||||
the rescan worker runs (needs `rescan_interval`). Quoted intent: `pkg/cache/cache.go` "A wait that times out serves the
|
||||
package unless FailClosed is set"; `scanner.go` "Scan failed on infrastructure, serving package; scan will be retried";
|
||||
production config "A scan that fails on infrastructure is retried and the package is served (fail_closed false)".
|
||||
Verdict: acceptable for production, whose only scanner is OSV, a remote service that cannot be made to time out by package
|
||||
content. Residual risk: with file-based scanners (trivy, grype, pip-audit) a crafted package that makes the scanner time out
|
||||
is served unscanned, because a deadline counts as infrastructure. Run those with `fail_closed: true`. No code change.
|
||||
|
||||
## Negative matrices (do not re-run)
|
||||
|
||||
| surface | runs | a leak would look like | verdict |
|
||||
|---------|------|------------------------|---------|
|
||||
| frontend nginx blocklist (`Dockerfile.frontend` template on nginx:alpine, stub backend) | 30 raw paths: `//npm`, `/./npm`, `%6Epm`, `/api/../npm`, `/api/..%2fnpm`, `/health/..%2fnpm`, `/ws/..%2fnpm`, `/api/..\npm`, `/api/..;/npm`, `/api/%5c..%5cnpm`, `/api/..%252fnpm`, `/npm?x=1`, `/metrics/` and more | 200 from the backend for `/npm`, `/pypi`, `/go` or `/metrics` | all 404 or SPA. `/NPM/x` returns the SPA page, not the proxy. |
|
||||
| backend re-interpretation of the six paths nginx forwarded raw | `/api/..\npm/x`, `/api/..;/npm/x`, `/api/%5c..%5cnpm/x`, `/api/%2e%2e%5cnpm/x`, `/api/..%252fnpm/x`, `/api/;/../npm/x` against the full app | 200 from the npm handler | all 404 |
|
||||
| WebSocket origin check | `Access.default_port_equivalent`, `scheme_mismatch_rejected`, `port_mismatch_rejected`, `glob_rejects_label_prefix`, `glob_rejects_suffix_trick` | an origin outside the allowlist accepted | clean. Same-origin mode compares host only; documented: "the Origin host must match the Host header". |
|
||||
| history totals under eviction | existing `TestPostgresHistoryTablesHaveNoPackageForeignKey`, `checkDeleteKeepsDownloadHistory` | totals fall after a package delete | clean: history tables carry no foreign key to packages. |
|
||||
@@ -0,0 +1,6 @@
|
||||
import Gohoarder.Cache
|
||||
import Gohoarder.Keys
|
||||
import Gohoarder.Security
|
||||
import Gohoarder.Access
|
||||
import Gohoarder.Release
|
||||
import Gohoarder.Stats
|
||||
@@ -0,0 +1,151 @@
|
||||
import Mathlib
|
||||
|
||||
/-!
|
||||
# Access control and upstream fetch guards
|
||||
|
||||
Models `pkg/app/app.go` `buildCheckOrigin` / `normalizeOriginHost`, `pkg/app/handlers_admin.go`
|
||||
`requireAdmin`, `pkg/auth/auth.go` (`getPermissionsForRole`, `ValidateAPIKey` expiry),
|
||||
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards), `Dockerfile.frontend`.
|
||||
Omits: the TLS layer, bcrypt internals, DNS.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Access
|
||||
|
||||
/-! ### WebSocket origin -/
|
||||
|
||||
inductive Scheme | http | https
|
||||
deriving DecidableEq
|
||||
|
||||
def defaultPort : Scheme → ℕ
|
||||
| Scheme.http => 80
|
||||
| Scheme.https => 443
|
||||
|
||||
/-- An origin after `strings.ToLower`: host labels plus an optional explicit port. -/
|
||||
structure Origin where
|
||||
scheme : Scheme
|
||||
host : List Char
|
||||
port : Option ℕ
|
||||
|
||||
/-- `normalizeOriginHost`: a port equal to the scheme default is dropped; compare on the effective port. -/
|
||||
def effPort (o : Origin) : ℕ := o.port.getD (defaultPort o.scheme)
|
||||
|
||||
/-- An exact allowlist rule matches iff scheme, host and effective port agree (`buildCheckOrigin`). -/
|
||||
def matchesExact (rule o : Origin) : Bool :=
|
||||
decide (rule.scheme = o.scheme) && decide (rule.host = o.host) && decide (effPort rule = effPort o)
|
||||
|
||||
theorem default_port_equivalent (s : Scheme) (h : List Char) :
|
||||
matchesExact ⟨s, h, none⟩ ⟨s, h, some (defaultPort s)⟩ = true := by
|
||||
simp [matchesExact, effPort]
|
||||
|
||||
theorem scheme_mismatch_rejected (rule o : Origin) (h : rule.scheme ≠ o.scheme) :
|
||||
matchesExact rule o = false := by
|
||||
simp [matchesExact, h]
|
||||
|
||||
theorem port_mismatch_rejected (s : Scheme) (h : List Char) (p q : ℕ) (hp : p ≠ q) :
|
||||
matchesExact ⟨s, h, some p⟩ ⟨s, h, some q⟩ = false := by
|
||||
simp [matchesExact, effPort, hp]
|
||||
|
||||
/-- Wildcard rule `https://*.d`: `strings.HasSuffix(host, ".d")` or host = `d`. -/
|
||||
def matchesGlob (d host : List Char) : Bool :=
|
||||
decide (host = d) || decide (('.' :: d) <:+ host)
|
||||
|
||||
/-- The leading dot pins the match to a label boundary: `evilexample.com` is not under `example.com`. -/
|
||||
theorem glob_rejects_label_prefix :
|
||||
matchesGlob "example.com".toList "evilexample.com".toList = false := by decide
|
||||
|
||||
theorem glob_accepts_subdomain :
|
||||
matchesGlob "example.com".toList "app.example.com".toList = true := by decide
|
||||
|
||||
theorem glob_rejects_suffix_trick :
|
||||
matchesGlob "example.com".toList "example.com.evil.net".toList = false := by decide
|
||||
|
||||
/-! ### Admin gate -/
|
||||
|
||||
inductive Role | readonly | readwrite | admin
|
||||
deriving DecidableEq
|
||||
|
||||
/-- `getPermissionsForRole`, restricted to the bypass-management and key-management permissions. -/
|
||||
def canManageBypasses : Role → Bool
|
||||
| Role.admin => true
|
||||
| _ => false
|
||||
|
||||
def canManageKeys : Role → Bool
|
||||
| Role.admin => true
|
||||
| _ => false
|
||||
|
||||
/-- `requireAdmin` admits a key with the admin role or the `bypasses:manage` permission; it also
|
||||
guards `/api/admin/keys`. No other role holds that permission, so no escalation to key minting. -/
|
||||
def requireAdminPasses (r : Role) : Bool := decide (r = Role.admin) || canManageBypasses r
|
||||
|
||||
theorem admin_gate_implies_key_manager (r : Role) (h : requireAdminPasses r = true) :
|
||||
canManageKeys r = true := by
|
||||
cases r <;> simp_all [requireAdminPasses, canManageBypasses, canManageKeys]
|
||||
|
||||
/-- `ValidateAPIKey`: a key is a candidate iff it has no expiry or `now <= expiresAt`. -/
|
||||
def keyLive (now : ℤ) (exp : Option ℤ) : Bool :=
|
||||
match exp with
|
||||
| none => true
|
||||
| some e => decide (now ≤ e)
|
||||
|
||||
theorem expired_key_rejected (now e : ℤ) (h : e < now) : keyLive now (some e) = false := by
|
||||
simp [keyLive, not_le.mpr h]
|
||||
|
||||
/-! ### PyPI `original_url` guards -/
|
||||
|
||||
/-- A fetch the handler would perform: host and file name of `original_url`. -/
|
||||
structure Fetch where
|
||||
host : String
|
||||
file : String
|
||||
|
||||
def allowedHosts : List String := ["pypi.org", "files.pythonhosted.org", "pythonhosted.org"]
|
||||
|
||||
/-- `isAllowedPyPIHost`: listed hosts, or a subdomain of pythonhosted.org (suffix on characters). -/
|
||||
def hostAllowed (h : String) : Bool :=
|
||||
decide (h ∈ allowedHosts) || decide (".pythonhosted.org".toList <:+ h.toList)
|
||||
|
||||
/-- Before the fix: host allowlist only. The cache key is `pypi/<name>/<requested file>`. -/
|
||||
def acceptsOld (f : Fetch) : Bool := hostAllowed f.host
|
||||
|
||||
/-- After the fix: the fetched file must be the requested one. -/
|
||||
def acceptsNew (requested : String) (f : Fetch) : Bool := hostAllowed f.host && decide (f.file = requested)
|
||||
|
||||
/-- Integrity of the cache key: what is stored under a key is the file the key names. -/
|
||||
theorem fixed_guard_binds_key (requested : String) (f : Fetch) (h : acceptsNew requested f = true) :
|
||||
f.file = requested := by
|
||||
simp only [acceptsNew, Bool.and_eq_true, decide_eq_true_eq] at h
|
||||
exact h.2
|
||||
|
||||
/-- Before the fix any file on an allowed host was stored under any requested name. -/
|
||||
theorem old_guard_allows_key_poisoning :
|
||||
∃ requested f, acceptsOld f = true ∧ f.file ≠ requested := by
|
||||
exact ⟨"requests-2.31.0-py3-none-any.whl", ⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl"⟩,
|
||||
by decide, by decide⟩
|
||||
|
||||
theorem internal_hosts_rejected :
|
||||
hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧
|
||||
hostAllowed "metadata.google.internal" = false := by decide
|
||||
|
||||
/-- The allowlist is checked once, on the first hop. `network.Client` follows redirects without
|
||||
re-checking, so an allowed host that answers 302 reaches any target. Acceptable only while no
|
||||
allowed host redirects (pypi.org and files.pythonhosted.org do not). -/
|
||||
def hopAllowed (hops : List String) : Bool := hops.head?.any hostAllowed
|
||||
|
||||
theorem redirect_escapes_allowlist :
|
||||
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = true ∧
|
||||
hostAllowed "169.254.169.254" = false := by decide
|
||||
|
||||
/-! ### Frontend blocklist (`Dockerfile.frontend`) -/
|
||||
|
||||
/-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/
|
||||
def blocked (first : String) (rest : String) : Bool :=
|
||||
decide (first ∈ ["npm", "pypi", "go", "metrics"]) && (decide (rest.toList = []) || decide (rest.toList.head? = some '/'))
|
||||
|
||||
theorem blocklist_covers_registries :
|
||||
blocked "npm" "/x" = true ∧ blocked "pypi" "" = true ∧ blocked "go" "/@v/list" = true ∧
|
||||
blocked "metrics" "" = true := by decide
|
||||
|
||||
/-- A prefix that merely starts with a registry name is not blocked, and is not proxied either: the
|
||||
`/health` and `/api/` locations are the only ones with a backend. -/
|
||||
theorem blocklist_is_segment_exact : blocked "npmx" "" = false := by decide
|
||||
|
||||
end Gohoarder.Access
|
||||
@@ -0,0 +1,211 @@
|
||||
import Mathlib
|
||||
|
||||
/-!
|
||||
# Cache lifecycle
|
||||
|
||||
Models `pkg/cache/cache.go`: `store` (expiry), `getOrFetch` and `Get` (hit path,
|
||||
retry), `purge` and `cleanup` (idle eviction), `evict` (LRU).
|
||||
What it omits: wall-clock skew, the storage backend, byte-level I/O.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Cache
|
||||
|
||||
/-! ### Expiry: artifacts never expire by age, metadata pages do -/
|
||||
|
||||
/-- `pkg/cache/cache.go` `store`: only metadata entries get `now + DefaultTTL`. -/
|
||||
def expiryFor (isMeta : Bool) (now ttl : ℤ) : Option ℤ :=
|
||||
if isMeta then some (now + ttl) else none
|
||||
|
||||
/-- `pkg/cache/cache.go` `getOrFetch`: `pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt)`. -/
|
||||
def expired (e : Option ℤ) (now : ℤ) : Prop := ∃ x, e = some x ∧ x < now
|
||||
|
||||
theorem artifact_never_expires (now ttl t : ℤ) : ¬ expired (expiryFor false now ttl) t := by
|
||||
simp [expiryFor, expired]
|
||||
|
||||
theorem metadata_expires_after_ttl (now ttl t : ℤ) (h : now + ttl < t) :
|
||||
expired (expiryFor true now ttl) t :=
|
||||
⟨now + ttl, by simp [expiryFor], h⟩
|
||||
|
||||
theorem metadata_fresh_within_ttl (now ttl t : ℤ) (h : t ≤ now + ttl) :
|
||||
¬ expired (expiryFor true now ttl) t := by
|
||||
simp only [expired, expiryFor, ite_true, Option.some.injEq, exists_eq_left']
|
||||
omega
|
||||
|
||||
/-! ### Idle eviction -/
|
||||
|
||||
/-- `pkg/cache/cache.go` `cleanup`: cutoff = now - IdleTTL; due iff `LastAccessed.Before(cutoff)`. -/
|
||||
def idleDue (now idleTTL lastAccessed : ℤ) : Prop := lastAccessed < now - idleTTL
|
||||
|
||||
theorem idle_keeps_recent (now idleTTL la : ℤ) (h : now - la ≤ idleTTL) :
|
||||
¬ idleDue now idleTTL la := by
|
||||
unfold idleDue; omega
|
||||
|
||||
theorem idle_removes_stale (now idleTTL la : ℤ) (h : idleTTL < now - la) :
|
||||
idleDue now idleTTL la := by
|
||||
unfold idleDue; omega
|
||||
|
||||
/-- A request refreshes `LastAccessed` (`UpdateDownloadCount`), so a hit is never idle-due at that instant. -/
|
||||
theorem touch_defers_idle (now idleTTL : ℤ) (h : 0 ≤ idleTTL) : ¬ idleDue now idleTTL now := by
|
||||
unfold idleDue; omega
|
||||
|
||||
/-! ### Interleavings of a hit and a purge -/
|
||||
|
||||
/-- One step of the concurrent schedule on a single entry. -/
|
||||
inductive Step
|
||||
| touch (t : ℤ) -- a request refreshes LastAccessed
|
||||
| check -- purge's `stillDue` re-read
|
||||
| del -- purge's `deletePackage`
|
||||
deriving DecidableEq
|
||||
|
||||
structure World where
|
||||
last : ℤ
|
||||
present : Bool
|
||||
checked : Bool -- the last `check` found the entry due
|
||||
deriving DecidableEq
|
||||
|
||||
def run (cutoff : ℤ) : World → List Step → World
|
||||
| w, [] => w
|
||||
| w, Step.touch t :: s => run cutoff { w with last := t } s
|
||||
| w, Step.check :: s => run cutoff { w with checked := decide (w.last < cutoff) } s
|
||||
| w, Step.del :: s => run cutoff { w with present := if w.checked then false else w.present } s
|
||||
|
||||
/-- Check and delete are two steps (`purge`: `stillDue(current)` then `deletePackage`), so a
|
||||
request between them is lost: the entry is deleted although `LastAccessed >= cutoff`. This is
|
||||
the window `Get` now covers with its retry. -/
|
||||
theorem purge_window_deletes_fresh_entry :
|
||||
let w := run 10 ⟨0, true, false⟩ [Step.check, Step.touch 20, Step.del]
|
||||
w.present = false ∧ 10 ≤ w.last := by
|
||||
decide
|
||||
|
||||
/-- With no request inside the window the purge honours `stillDue`. -/
|
||||
theorem purge_without_window_keeps_fresh (cutoff t : ℤ) (h : cutoff ≤ t) :
|
||||
(run cutoff ⟨0, true, false⟩ [Step.touch t, Step.check, Step.del]).present = true := by
|
||||
simp [run, not_lt.mpr h]
|
||||
|
||||
/-! ### `Get`: probe, then open -/
|
||||
|
||||
inductive Outcome | served | refetched | error
|
||||
deriving DecidableEq
|
||||
|
||||
/-- Before the fix: probe in `getOrFetch`, open after the singleflight; `purgedBetween` is a delete
|
||||
between the two. -/
|
||||
def getOnce (present purgedBetween : Bool) : Outcome :=
|
||||
if present then (if purgedBetween then Outcome.error else Outcome.served) else Outcome.refetched
|
||||
|
||||
/-- `Get` with `getAttempts = 2`: the second pass re-probes the (now missing) blob and fetches. -/
|
||||
def getRetry (present d1 d2 : Bool) : Outcome :=
|
||||
match getOnce present d1 with
|
||||
| Outcome.error => if d2 then Outcome.error else Outcome.refetched
|
||||
| o => o
|
||||
|
||||
theorem getOnce_errors_on_purge : getOnce true true = Outcome.error := rfl
|
||||
|
||||
/-- At most one purge per `Get` never reaches the client as an error. -/
|
||||
theorem getRetry_survives_one_purge (present d1 d2 : Bool) (h : ¬ (d1 = true ∧ d2 = true)) :
|
||||
getRetry present d1 d2 ≠ Outcome.error := by
|
||||
cases present <;> cases d1 <;> cases d2 <;> simp_all [getRetry, getOnce]
|
||||
|
||||
/-! ### LRU eviction -/
|
||||
|
||||
/-- `evict`: delete oldest first until `freed >= needed`; `sizes` is the oldest-first listing. -/
|
||||
def evictFreed : List ℕ → ℕ → ℕ
|
||||
| [], _ => 0
|
||||
| s :: rest, needed => if needed = 0 then 0 else s + evictFreed rest (needed - s)
|
||||
|
||||
theorem evictFreed_le_total (sizes : List ℕ) (needed : ℕ) : evictFreed sizes needed ≤ sizes.sum := by
|
||||
induction sizes generalizing needed with
|
||||
| nil => simp [evictFreed]
|
||||
| cons s rest ih =>
|
||||
unfold evictFreed
|
||||
split_ifs
|
||||
· simp
|
||||
· simp only [List.sum_cons]; have := ih (needed - s); omega
|
||||
|
||||
theorem evictFreed_ge (sizes : List ℕ) (needed : ℕ) (h : needed ≤ sizes.sum) :
|
||||
needed ≤ evictFreed sizes needed := by
|
||||
induction sizes generalizing needed with
|
||||
| nil => simpa [evictFreed] using h
|
||||
| cons s rest ih =>
|
||||
unfold evictFreed
|
||||
split_ifs with h0
|
||||
· omega
|
||||
· simp only [List.sum_cons] at h
|
||||
have := ih (needed - s) (by omega)
|
||||
omega
|
||||
|
||||
/-- After `store` evicts for `needed = used + size - limit` and the listing held enough bytes,
|
||||
usage including the new entry is within the cap. -/
|
||||
theorem lru_keeps_cap (used size limit : ℕ) (sizes : List ℕ)
|
||||
(hroom : used + size - limit ≤ sizes.sum) :
|
||||
used + size - evictFreed sizes (used + size - limit) ≤ limit := by
|
||||
have h1 := evictFreed_ge sizes (used + size - limit) hroom
|
||||
omega
|
||||
|
||||
/-- When the listing cannot free enough (`freed < needed`) `evict` still returns nil, so the cap
|
||||
rests on the backend's `Put` quota check (`filesystem.go` `Put`). The hypothesis of `lru_keeps_cap`
|
||||
fails here, and the result exceeds the cap. -/
|
||||
theorem lru_cap_needs_enough_evictable :
|
||||
∃ used size limit : ℕ, ∃ sizes : List ℕ,
|
||||
used + size - evictFreed sizes (used + size - limit) > limit := by
|
||||
exact ⟨100, 10, 100, [5], by decide⟩
|
||||
|
||||
/-- The entry being stored is not in the metadata listing (`SavePackage` runs after `Put`), so
|
||||
eviction never deletes it. -/
|
||||
theorem evict_spares_unlisted (listed : List String) (new : String) (h : new ∉ listed) :
|
||||
∀ victim ∈ listed.take 100, victim ≠ new := by
|
||||
intro v hv hv'
|
||||
exact h (hv' ▸ List.mem_of_mem_take hv)
|
||||
|
||||
/-- One eviction pass: `n` listed rows of which `d` can be deleted; the rest are listed again. -/
|
||||
def passRemaining (n d : ℕ) : ℕ := n - d
|
||||
|
||||
/-- Before the fix the loop continued on `n >= limit` only; a pass that deletes nothing re-lists
|
||||
the same rows and never ends. -/
|
||||
theorem old_evict_is_stuck (n : ℕ) : passRemaining n 0 = n := by simp [passRemaining]
|
||||
|
||||
/-- After the fix a pass continues only if it deleted a row, so the row count strictly falls. -/
|
||||
theorem fixed_evict_measure_falls (n d : ℕ) (hd : 0 < d) (hdn : d ≤ n) : passRemaining n d < n := by
|
||||
unfold passRemaining; omega
|
||||
|
||||
/-! ### Quota accounting: overwriting a key
|
||||
|
||||
`pkg/storage/filesystem/filesystem.go` `Put`: `fs.used` tracks bytes on disk. -/
|
||||
|
||||
/-- After the fix: an overwrite releases the bytes of the file it replaces. -/
|
||||
def usedAfterPut (used replaced written : ℕ) : ℕ := used - replaced + written
|
||||
|
||||
/-- Before the fix: the replaced bytes stayed counted. -/
|
||||
def usedAfterPutOld (used written : ℕ) : ℕ := used + written
|
||||
|
||||
/-- If `used` is the sum of the stored sizes, `other + replaced`, the counter stays exact. -/
|
||||
theorem put_keeps_usage_exact (other replaced written : ℕ) :
|
||||
usedAfterPut (other + replaced) replaced written = other + written := by
|
||||
unfold usedAfterPut; omega
|
||||
|
||||
/-- Two writes of one key (400 then 300 bytes) leave 700 counted, 300 on disk. -/
|
||||
theorem old_put_inflates_usage : usedAfterPutOld (usedAfterPutOld 0 400) 300 = 700 ∧
|
||||
usedAfterPut (usedAfterPut 0 0 400) 400 300 = 300 := by decide
|
||||
|
||||
/-! ### Which entries skip the scan
|
||||
|
||||
`pkg/metadata/interface.go` `IsMetadataEntry`; the scan gate in `getOrFetch` and `store`. -/
|
||||
|
||||
def metaVersions : List String := ["list", "page", "latest", "metadata"]
|
||||
|
||||
/-- After the fix the `.mod` / `.info` name suffix exempts Go entries only. -/
|
||||
def scanExempt (registry : String) (nameSuffixMeta : Bool) (version : String) : Bool :=
|
||||
decide (version ∈ metaVersions) || (decide (registry = "go") && nameSuffixMeta)
|
||||
|
||||
/-- Before the fix the suffix exempted any registry. -/
|
||||
def scanExemptOld (nameSuffixMeta : Bool) (version : String) : Bool :=
|
||||
decide (version ∈ metaVersions) || nameSuffixMeta
|
||||
|
||||
theorem npm_named_like_go_metadata_is_scanned (v : String) (hv : v ∉ metaVersions) :
|
||||
scanExempt "npm" true v = false := by
|
||||
simp [scanExempt, hv]
|
||||
|
||||
theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decide
|
||||
|
||||
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
|
||||
|
||||
end Gohoarder.Cache
|
||||
@@ -0,0 +1,146 @@
|
||||
import Mathlib
|
||||
|
||||
/-!
|
||||
# Storage keys, path safety, canonicalisation
|
||||
|
||||
Models `pkg/cache/cache.go` `generateStorageKey`, `pkg/storage/filesystem/filesystem.go`
|
||||
`keyToPath`, `pkg/proxy/npm/npm.go` `CanonicalPath`, and `pkg/proxy/pypi/pypi.go`
|
||||
`extractVersionFromFilename`. Omits: symlinks (the store writes through `os.Root`), Unicode.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Keys
|
||||
|
||||
/-! ### `keyToPath`: segment normalisation -/
|
||||
|
||||
/-- `filepath.Clean` plus the strip loop in `keyToPath`: `.` and empty segments vanish, `..` pops
|
||||
a segment and is dropped at the root. Segments are kept in reverse order. -/
|
||||
def cleanRev : List String → List String → List String
|
||||
| acc, [] => acc
|
||||
| acc, seg :: rest =>
|
||||
if seg = "." ∨ seg = "" then cleanRev acc rest
|
||||
else if seg = ".." then cleanRev acc.tail rest
|
||||
else cleanRev (seg :: acc) rest
|
||||
|
||||
def clean (segs : List String) : List String := (cleanRev [] segs).reverse
|
||||
|
||||
theorem cleanRev_no_dotdot (segs acc : List String) (h : ".." ∉ acc) : ".." ∉ cleanRev acc segs := by
|
||||
induction segs generalizing acc with
|
||||
| nil => simpa [cleanRev] using h
|
||||
| cons seg rest ih =>
|
||||
unfold cleanRev
|
||||
split_ifs with h1 h2
|
||||
· exact ih acc h
|
||||
· exact ih acc.tail (fun hm => h (List.mem_of_mem_tail hm))
|
||||
· apply ih
|
||||
simp only [List.mem_cons, not_or]
|
||||
exact ⟨fun e => h2 e.symm, h⟩
|
||||
|
||||
/-- No cleaned key contains a `..` segment, so the joined path stays under the store root. -/
|
||||
theorem clean_stays_in_root (segs : List String) : ".." ∉ clean segs := by
|
||||
unfold clean
|
||||
simpa using cleanRev_no_dotdot segs [] (by simp)
|
||||
|
||||
/-- The sanitiser rewrites; it does not reject. Distinct keys collapse onto one path. -/
|
||||
theorem keyToPath_not_injective :
|
||||
clean ["npm", "pkg", "..", "other", "1.0.0"] = clean ["npm", "other", "1.0.0"] ∧
|
||||
["npm", "pkg", "..", "other", "1.0.0"] ≠ ["npm", "other", "1.0.0"] := by
|
||||
decide
|
||||
|
||||
theorem keyToPath_traversal_is_clamped :
|
||||
clean ["..", "..", "etc", "passwd"] = ["etc", "passwd"] := by decide
|
||||
|
||||
/-! ### Key injectivity: `registry/name/version` -/
|
||||
|
||||
/-- `generateStorageKey`: join with `/`. -/
|
||||
def key (registry name version : String) : List String := [registry, name, version]
|
||||
|
||||
/-- Over segment lists the tuple is recoverable; `String.intercalate "/"` is injective exactly
|
||||
when the parts contain no `/`. -/
|
||||
theorem key_injective (r n v r' n' v' : String) (h : key r n v = key r' n' v') :
|
||||
r = r' ∧ n = n' ∧ v = v' := by
|
||||
simp only [key, List.cons.injEq, and_true] at h
|
||||
exact ⟨h.1, h.2.1, h.2.2⟩
|
||||
|
||||
/-- With `/` inside a part the joined string collides: npm `@x/y` + `b` and `@x` + `y/b`. The
|
||||
second tuple needs an upstream 200 at a path npm never serves, so the proxy cannot store it. -/
|
||||
theorem joined_key_collides_with_slash :
|
||||
String.intercalate "/" ["npm", "@x/y", "b"] = String.intercalate "/" ["npm", "@x", "y/b"] := by
|
||||
decide
|
||||
|
||||
/-! ### `npm.CanonicalPath`: escaped scope separator -/
|
||||
|
||||
inductive Tok | scope | esc | sl | other
|
||||
deriving DecidableEq
|
||||
|
||||
/-- Rewrites the first escaped `/` of the first segment (`CanonicalPath`'s `strings.Cut`). -/
|
||||
def rewriteFirst : List Tok → List Tok
|
||||
| [] => []
|
||||
| Tok.sl :: r => Tok.sl :: r
|
||||
| Tok.esc :: r => Tok.sl :: r
|
||||
| Tok.scope :: r => Tok.scope :: rewriteFirst r
|
||||
| Tok.other :: r => Tok.other :: rewriteFirst r
|
||||
|
||||
/-- `CanonicalPath` acts only on a segment starting with `@`. -/
|
||||
def canon : List Tok → List Tok
|
||||
| Tok.scope :: r => Tok.scope :: rewriteFirst r
|
||||
| p => p
|
||||
|
||||
theorem rewriteFirst_idem (r : List Tok) : rewriteFirst (rewriteFirst r) = rewriteFirst r := by
|
||||
induction r with
|
||||
| nil => rfl
|
||||
| cons t rest ih => cases t <;> simp [rewriteFirst, ih]
|
||||
|
||||
/-- Canonicalisation is idempotent: a second pass finds the separator the first one wrote. -/
|
||||
theorem canon_idem (p : List Tok) : canon (canon p) = canon p := by
|
||||
cases p with
|
||||
| nil => rfl
|
||||
| cons t r => cases t <;> simp [canon, rewriteFirst_idem]
|
||||
|
||||
/-- The rewrite adds at most one separator, so a name cannot smuggle extra path segments. -/
|
||||
theorem rewriteFirst_adds_one_sep (r : List Tok) :
|
||||
(rewriteFirst r).count Tok.sl ≤ r.count Tok.sl + 1 := by
|
||||
induction r with
|
||||
| nil => simp [rewriteFirst]
|
||||
| cons t rest ih =>
|
||||
cases t <;> simp [rewriteFirst, List.count_cons] at * <;> omega
|
||||
|
||||
theorem canon_adds_one_sep (p : List Tok) : (canon p).count Tok.sl ≤ p.count Tok.sl + 1 := by
|
||||
cases p with
|
||||
| nil => simp [canon]
|
||||
| cons t r =>
|
||||
have := rewriteFirst_adds_one_sep r
|
||||
cases t <;> simp [canon, List.count_cons] at * <;> omega
|
||||
|
||||
/-- The escape that survives in the name part (`@a%2fb%2fc` gives `@a/b%2fc`) is later rejected:
|
||||
Fiber answers 404 to an escaped slash, which `TestNPMScopedNames` and the traversal probe
|
||||
(`/npm/@s%2fn%2f..%2f..%2fx` returns 404) exercise. -/
|
||||
theorem canon_keeps_later_escape :
|
||||
canon [Tok.scope, Tok.esc, Tok.other, Tok.esc, Tok.other] =
|
||||
[Tok.scope, Tok.sl, Tok.other, Tok.esc, Tok.other] := by decide
|
||||
|
||||
/-! ### PyPI version from a file name -/
|
||||
|
||||
/-- Wheel (PEP 427): the version is the second `-` segment when it starts with a digit. -/
|
||||
def startsWithDigit (v : String) : Bool :=
|
||||
match v.toList with
|
||||
| c :: _ => c.isDigit
|
||||
| [] => false
|
||||
|
||||
def wheelVersion (segs : List String) : Option String :=
|
||||
match segs with
|
||||
| _ :: v :: _ => if startsWithDigit v then some v else none
|
||||
| _ => none
|
||||
|
||||
/-- A well-formed wheel name `dist-version-...` yields its version, whatever follows. -/
|
||||
theorem wheelVersion_correct (d v : String) (rest : List String) (hv : startsWithDigit v = true) :
|
||||
wheelVersion (d :: v :: rest) = some v := by
|
||||
simp [wheelVersion, hv]
|
||||
|
||||
/-- The cache version for a PyPI file is the file name, which is unique per file, while the
|
||||
release version is shared by all files of a release (`release_version`). Two files of one release
|
||||
have different keys and one release key: bypasses by release cover both, by design. -/
|
||||
theorem pypi_key_per_file_release_shared (name f1 f2 : String) (h : f1 ≠ f2) :
|
||||
key "pypi" name f1 ≠ key "pypi" name f2 := by
|
||||
intro e; exact h (key_injective _ _ _ _ _ _ e).2.2
|
||||
|
||||
end Gohoarder.Keys
|
||||
@@ -0,0 +1,63 @@
|
||||
import Mathlib
|
||||
|
||||
/-!
|
||||
# Release-age passthrough
|
||||
|
||||
Models `pkg/proxy/npm/npm.go` `rewriteMetadataURLs`, `pkg/proxy/pypi/simple_json.go`
|
||||
`rewriteJSONPage`, and the packument/index freshness TTL in `pkg/cache/cache.go`. A client gate
|
||||
accepts a version when `now - publishedAt >= gate`. Omits: JSON parsing, number formatting.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Release
|
||||
|
||||
/-- A JSON object as key/value pairs. -/
|
||||
abbrev Obj := List (String × String)
|
||||
|
||||
/-- `rewriteJSONPage`: only the `url` value of a file entry changes. -/
|
||||
def rewriteFile (proxy : String) (o : Obj) : Obj :=
|
||||
o.map fun kv => if kv.1 = "url" then (kv.1, proxy) else kv
|
||||
|
||||
theorem rewrite_preserves_upload_time (proxy : String) (o : Obj) (t : String)
|
||||
(h : ("upload-time", t) ∈ o) : ("upload-time", t) ∈ rewriteFile proxy o := by
|
||||
unfold rewriteFile
|
||||
exact List.mem_map.mpr ⟨("upload-time", t), h, by simp⟩
|
||||
|
||||
theorem rewrite_preserves_other_keys (proxy : String) (o : Obj) (k v : String) (hk : k ≠ "url")
|
||||
(h : (k, v) ∈ o) : (k, v) ∈ rewriteFile proxy o := by
|
||||
unfold rewriteFile
|
||||
exact List.mem_map.mpr ⟨(k, v), h, by simp [hk]⟩
|
||||
|
||||
theorem rewrite_keeps_keys (proxy : String) (o : Obj) : (rewriteFile proxy o).map Prod.fst = o.map Prod.fst := by
|
||||
unfold rewriteFile
|
||||
simp only [List.map_map]
|
||||
congr 1
|
||||
funext kv
|
||||
simp only [Function.comp]
|
||||
split_ifs <;> simp
|
||||
|
||||
/-! ### Staleness against a minimum-age gate -/
|
||||
|
||||
/-- The gate accepts a version published at `t` when it is at least `gate` old. -/
|
||||
def gateAccepts (gate now t : ℤ) : Prop := gate ≤ now - t
|
||||
|
||||
/-- A version missing from a snapshot taken at `s` was published after `s`. If the snapshot is at
|
||||
most `ttl` old and `ttl <= gate`, the missing version is younger than the gate, so the gate would
|
||||
have refused it anyway: staleness hides nothing the gate allows. -/
|
||||
theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ ttl) (httl : ttl ≤ gate)
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t := by
|
||||
unfold gateAccepts; omega
|
||||
|
||||
/-- Production: `default_ttl: 24h` against a 72h gate. -/
|
||||
theorem prod_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
|
||||
|
||||
/-- The compiled default is 7 days. Against a 72h gate a version aged 84h is eligible but absent
|
||||
from a 7-day-old snapshot: the proxy withholds it, which is stricter than the gate, never looser. -/
|
||||
theorem default_ttl_exceeds_gate :
|
||||
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
|
||||
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
|
||||
|
||||
/-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/
|
||||
theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t :=
|
||||
Iff.rfl
|
||||
|
||||
end Gohoarder.Release
|
||||
@@ -0,0 +1,200 @@
|
||||
import Mathlib
|
||||
|
||||
/-!
|
||||
# Security decision logic
|
||||
|
||||
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `scheduleRetry`,
|
||||
`pkg/metadata/gormstore/gormstore_v2.go` `GetActiveCVEBypasses`, and the scan gate in
|
||||
`pkg/cache/cache.go` `getOrFetch`. Severities are ranks (low 1 .. critical 4). Omits: the
|
||||
scanners themselves, threshold counters (`block_thresholds`), network.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Security
|
||||
|
||||
structure Vuln where
|
||||
id : ℕ
|
||||
sev : ℕ
|
||||
|
||||
structure Bypass where
|
||||
cve : ℕ
|
||||
covers : Bool -- `AppliesTo` empty or equal to this package
|
||||
active : Bool
|
||||
expiresAt : ℤ
|
||||
|
||||
/-- `GetActiveCVEBypasses`: `active = true AND expires_at > now`. -/
|
||||
def activeAt (now : ℤ) (b : Bypass) : Bool := b.active && decide (now < b.expiresAt)
|
||||
|
||||
def bypassedIds (now : ℤ) (bs : List Bypass) : List ℕ :=
|
||||
(bs.filter fun b => activeAt now b && b.covers).map (·.cve)
|
||||
|
||||
/-- The vulnerabilities no bypass covers (`severityCounts` loop). -/
|
||||
def remaining (now : ℤ) (bs : List Bypass) (vs : List Vuln) : List Vuln :=
|
||||
vs.filter fun v => decide (v.id ∉ bypassedIds now bs)
|
||||
|
||||
/-- `block_on_severity`: `none` for "none"/empty, else block when a remaining vulnerability has
|
||||
rank at or above the threshold. -/
|
||||
def blocksBySeverity (policy : Option ℕ) (vs : List Vuln) : Bool :=
|
||||
match policy with
|
||||
| none => false
|
||||
| some t => vs.any fun v => decide (t ≤ v.sev)
|
||||
|
||||
def decideSev (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) : Bool :=
|
||||
blocksBySeverity policy (remaining now bs vs)
|
||||
|
||||
/-- The LOW branch before the fix: `len(result.Vulnerabilities) > 0`, bypasses ignored. -/
|
||||
def decideLowOld (vs : List Vuln) : Bool := decide (0 < vs.length)
|
||||
|
||||
theorem expired_bypass_inactive (now : ℤ) (b : Bypass) (h : b.expiresAt ≤ now) : activeAt now b = false := by
|
||||
simp [activeAt, not_lt.mpr h]
|
||||
|
||||
theorem inactive_bypass_ignored (now : ℤ) (b : Bypass) (h : b.active = false) : activeAt now b = false := by
|
||||
simp [activeAt, h]
|
||||
|
||||
/-- Every vulnerability bypassed by an active, covering bypass: nothing blocks, for any policy. -/
|
||||
theorem fully_bypassed_never_blocks (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln)
|
||||
(h : ∀ v ∈ vs, v.id ∈ bypassedIds now bs) : decideSev policy now bs vs = false := by
|
||||
have : remaining now bs vs = [] := by
|
||||
simp only [remaining, List.filter_eq_nil_iff, decide_eq_true_eq, not_not]
|
||||
exact h
|
||||
simp [decideSev, this, blocksBySeverity]
|
||||
cases policy <;> simp
|
||||
|
||||
/-- A vulnerability at or above the policy that no active bypass covers blocks. -/
|
||||
theorem uncovered_vuln_blocks (t : ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln)
|
||||
(hv : v ∈ vs) (hsev : t ≤ v.sev) (hun : v.id ∉ bypassedIds now bs) :
|
||||
decideSev (some t) now bs vs = true := by
|
||||
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq]
|
||||
refine ⟨v, ?_, hsev⟩
|
||||
simp [remaining, hv, hun]
|
||||
|
||||
/-- Adding a bypass never turns an allow into a block. -/
|
||||
theorem bypass_monotone (policy : Option ℕ) (now : ℤ) (b : Bypass) (bs : List Bypass) (vs : List Vuln)
|
||||
(h : decideSev policy now (b :: bs) vs = true) : decideSev policy now bs vs = true := by
|
||||
cases policy with
|
||||
| none => simp [decideSev, blocksBySeverity] at h
|
||||
| some t =>
|
||||
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq, remaining,
|
||||
List.mem_filter] at h ⊢
|
||||
obtain ⟨v, ⟨hv, hn⟩, hs⟩ := h
|
||||
refine ⟨v, ⟨hv, ?_⟩, hs⟩
|
||||
intro hmem
|
||||
apply hn
|
||||
simp only [bypassedIds, List.filter_cons] at hmem ⊢
|
||||
split_ifs <;> simp_all
|
||||
|
||||
/-- Before the fix, LOW blocked a package whose only vulnerability was bypassed. -/
|
||||
theorem old_low_ignores_bypass :
|
||||
let vs := [Vuln.mk 1 1]
|
||||
let bs := [Bypass.mk 1 true true 100]
|
||||
decideLowOld vs = true ∧ decideSev (some 1) 0 bs vs = false := by
|
||||
decide
|
||||
|
||||
/-! ### Serve decision -/
|
||||
|
||||
inductive Scan
|
||||
| missing (inflight : Bool) -- no result row; `isInflight` while a scan runs
|
||||
| err (infra : Bool) -- every scanner failed
|
||||
| ok (vs : List Vuln)
|
||||
|
||||
/-- `CheckVulnerabilities` and the gate: `true` means the package is served. -/
|
||||
def serves (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
|
||||
Scan → Bool
|
||||
| s =>
|
||||
if pkgBypass then true else
|
||||
match s with
|
||||
| Scan.missing inflight => !failClosed && inflight
|
||||
| Scan.err infra => !failClosed && infra
|
||||
| Scan.ok vs => !decideSev policy now bs vs
|
||||
|
||||
theorem fail_closed_blocks_without_verdict (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (s : Scan)
|
||||
(hs : (∃ i, s = Scan.missing i) ∨ (∃ i, s = Scan.err i)) :
|
||||
serves true false policy now bs s = false := by
|
||||
rcases hs with ⟨i, rfl⟩ | ⟨i, rfl⟩ <;> simp [serves]
|
||||
|
||||
/-- A vulnerable package is not served when policy blocks, unless a package bypass covers it. -/
|
||||
theorem vulnerable_not_served (policy : Option ℕ) (t : ℕ) (hp : policy = some t) (failClosed : Bool)
|
||||
(now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
|
||||
(hun : v.id ∉ bypassedIds now bs) :
|
||||
serves failClosed false policy now bs (Scan.ok vs) = false := by
|
||||
subst hp
|
||||
simp [serves, uncovered_vuln_blocks t now bs vs v hv hsev hun]
|
||||
|
||||
/-- With `fail_closed = false`, exactly these states serve a package with no verdict: a scan in
|
||||
flight, or every scanner failing on infrastructure. A package bypass serves in any state. -/
|
||||
theorem unscanned_served_iff (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
|
||||
(bs : List Bypass) (i : Bool) :
|
||||
(serves failClosed pkgBypass policy now bs (Scan.missing i) = true ↔
|
||||
pkgBypass = true ∨ (failClosed = false ∧ i = true)) ∧
|
||||
(serves failClosed pkgBypass policy now bs (Scan.err i) = true ↔
|
||||
pkgBypass = true ∨ (failClosed = false ∧ i = true)) := by
|
||||
cases failClosed <;> cases pkgBypass <;> cases i <;> simp [serves]
|
||||
|
||||
/-- The infra-error record never changes with retries, so the package stays served. -/
|
||||
theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
|
||||
serves false false policy now bs (Scan.err true) = true := by
|
||||
simp [serves]
|
||||
|
||||
/-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/
|
||||
def servesDisabled : Bool := true
|
||||
|
||||
/-! ### Retry budget -/
|
||||
|
||||
def maxRetries : ℕ := 6
|
||||
def retryIntervalMin : ℕ := 5
|
||||
|
||||
/-- Scans run from `attempt`: `scan` schedules attempt+1 only when infra-only and `attempt < maxRetries`. -/
|
||||
def scansFrom : ℕ → ℕ
|
||||
| 0 => 1
|
||||
| k + 1 => 1 + scansFrom k
|
||||
|
||||
theorem scansFrom_eq (k : ℕ) : scansFrom k = k + 1 := by
|
||||
induction k with
|
||||
| zero => rfl
|
||||
| succ k ih => simp only [scansFrom, ih]; omega
|
||||
|
||||
theorem scans_total : scansFrom maxRetries = maxRetries + 1 := scansFrom_eq _
|
||||
|
||||
theorem retry_window_minutes : maxRetries * retryIntervalMin = 30 := by decide
|
||||
|
||||
/-- The attempt counter is bounded, so a package that keeps failing on infrastructure is scanned at most 7 times. -/
|
||||
theorem retry_terminates (attempt : ℕ) : scansFrom (maxRetries - attempt) ≤ maxRetries + 1 := by
|
||||
rw [scansFrom_eq]; omega
|
||||
|
||||
/-! ### Which version scanners are asked about
|
||||
|
||||
`pkg/scanner/scanner.go` `scanVersion`: PyPI artifacts are cached under their file name. -/
|
||||
|
||||
def scanVersion (release cacheVersion : String) : String :=
|
||||
if release = "" then cacheVersion else release
|
||||
|
||||
theorem scan_asks_release_version (release cacheVersion : String) (h : release ≠ "") :
|
||||
scanVersion release cacheVersion = release := by
|
||||
simp [scanVersion, h]
|
||||
|
||||
theorem npm_scan_keeps_cache_version (cacheVersion : String) :
|
||||
scanVersion "" cacheVersion = cacheVersion := by
|
||||
simp [scanVersion]
|
||||
|
||||
/-- Before the fix scanners received the file name, which is never a release version. -/
|
||||
theorem file_name_is_not_release_version :
|
||||
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
|
||||
|
||||
/-! ### Merge: worst status wins, but a failed scanner leaves no trace -/
|
||||
|
||||
/-- ranks: clean 0, pending 1, error 2, vulnerable 3 (`mergeResults`). -/
|
||||
def mergeRank (xs : List ℕ) : ℕ := xs.foldr max 0
|
||||
|
||||
theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRank xs := by
|
||||
induction xs with
|
||||
| nil => simp at h
|
||||
| cons y ys ih =>
|
||||
simp only [mergeRank, List.foldr_cons]
|
||||
rcases List.mem_cons.mp h with rfl | h
|
||||
· exact le_max_left _ _
|
||||
· exact le_trans (ih h) (le_max_right _ _)
|
||||
|
||||
/-- Results exist only for scanners that returned; with one scanner failing and one clean, the
|
||||
merged status is clean and no retry is scheduled (`scan`: retry only when no scanner succeeded). -/
|
||||
theorem partial_failure_reads_clean : mergeRank [0] = 0 := by decide
|
||||
|
||||
end Gohoarder.Security
|
||||
@@ -0,0 +1,90 @@
|
||||
import Mathlib
|
||||
|
||||
/-!
|
||||
# Stats and time series
|
||||
|
||||
Models `pkg/metadata/gormstore/aggregation_worker.go` (`AggregateHourly`, `AggregateDaily`) and
|
||||
`pkg/metadata/gormstore/gormstore_v2.go` `GetTimeSeriesStats`. Time is in whole minutes since the
|
||||
epoch; an hour is 60 minutes and a day 24 hours. Omits: unique IPs, packages, registries.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Stats
|
||||
|
||||
/-! ### Hourly pass: each event is counted once -/
|
||||
|
||||
/-- `AggregateHourly`: cutoff hour = floor((now - 5min) / 60); events in earlier hours move to
|
||||
`hr` and are deleted, in one transaction. -/
|
||||
def cutoffHour (nowMin : ℤ) : ℤ := (nowMin - 5) / 60
|
||||
|
||||
def moveEvents (c : ℤ) (ev hr : ℤ → ℕ) : (ℤ → ℕ) × (ℤ → ℕ) :=
|
||||
(fun h => if h < c then 0 else ev h, fun h => hr h + if h < c then ev h else 0)
|
||||
|
||||
/-- Per hour, events plus hourly rows are unchanged by a pass: nothing is counted twice or dropped. -/
|
||||
theorem hourly_pass_conserves (c : ℤ) (ev hr : ℤ → ℕ) (h : ℤ) :
|
||||
(moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h = ev h + hr h := by
|
||||
simp only [moveEvents]
|
||||
split_ifs <;> omega
|
||||
|
||||
theorem hourly_pass_conserves_sum (c : ℤ) (ev hr : ℤ → ℕ) (S : Finset ℤ) :
|
||||
∑ h ∈ S, ((moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h) = ∑ h ∈ S, (ev h + hr h) :=
|
||||
Finset.sum_congr rfl fun h _ => hourly_pass_conserves c ev hr h
|
||||
|
||||
/-- Within five minutes after the hour the cutoff is still the previous hour, so the last hour of a
|
||||
day is not aggregated by a pass at `hh:00`-`hh:04`. -/
|
||||
theorem early_tick_leaves_last_hour (hourIdx m : ℤ) (hm0 : 0 ≤ m) (hm : m < 5) :
|
||||
cutoffHour (60 * hourIdx + m) = hourIdx - 1 := by
|
||||
unfold cutoffHour; omega
|
||||
|
||||
theorem late_tick_covers_last_hour (hourIdx m : ℤ) (hm0 : 5 ≤ m) (hm : m < 60) :
|
||||
cutoffHour (60 * hourIdx + m) = hourIdx := by
|
||||
unfold cutoffHour; omega
|
||||
|
||||
/-! ### Daily pass: which days are rolled up -/
|
||||
|
||||
def retentionDays : ℕ := 7
|
||||
/-- Days recomputed by each pass (`rollupDays`). -/
|
||||
def rollupDays : ℕ := 6
|
||||
|
||||
/-- A pass on day `t` rolls up day `d` (before: only yesterday). -/
|
||||
def oldRolls (t d : ℕ) : Prop := d + 1 = t
|
||||
def newRolls (t d : ℕ) : Prop := d + 1 ≤ t ∧ t ≤ d + rollupDays
|
||||
|
||||
theorem rollup_window_below_retention : rollupDays < retentionDays := by decide
|
||||
|
||||
/-- The pass on day `t` deletes hourly rows older than 7 days: hours of day `d` survive it
|
||||
whenever `t < d + 7`. The new window ends at `d + 6`, inside that bound. -/
|
||||
theorem new_window_inside_retention (t d : ℕ) (h : newRolls t d) : t < d + retentionDays := by
|
||||
unfold newRolls at h; unfold retentionDays rollupDays at *; omega
|
||||
|
||||
/-- A day is rolled up if some pass day (hour-0 tick) falls in its window. -/
|
||||
def covered (rolls : ℕ → ℕ → Prop) (passes : Set ℕ) (d : ℕ) : Prop := ∃ t ∈ passes, rolls t d
|
||||
|
||||
/-- Before: skipping the one pass on day d+1 (restart at midnight) loses day d for good. -/
|
||||
theorem old_loses_day_on_one_skip (d : ℕ) :
|
||||
¬ covered oldRolls {t | t ≠ d + 1} d := by
|
||||
rintro ⟨t, ht, h⟩
|
||||
unfold oldRolls at h
|
||||
exact ht h.symm
|
||||
|
||||
/-- After: any single surviving pass in the next six days repairs it. -/
|
||||
theorem new_repairs_after_skip (d : ℕ) : covered newRolls {t | t ≠ d + 1} d :=
|
||||
⟨d + 2, by simp, by unfold newRolls rollupDays; omega⟩
|
||||
|
||||
/-! ### Chart: rollup against hourly rows and events -/
|
||||
|
||||
/-- Before: `counts[day] = rollup`. After: the larger of rollup and hourly+events. -/
|
||||
def chartOld (rollup live : ℕ) : ℕ := rollup
|
||||
def chartNew (rollup live : ℕ) : ℕ := max rollup live
|
||||
|
||||
/-- Rollup and live (hourly rows + events) each count a subset of the day's downloads, so the
|
||||
larger is the better lower bound and never exceeds the truth. -/
|
||||
theorem chartNew_sound (truth rollup live : ℕ) (hr : rollup ≤ truth) (hl : live ≤ truth) :
|
||||
chartNew rollup live ≤ truth := max_le hr hl
|
||||
|
||||
theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ chartNew rollup live :=
|
||||
le_max_left _ _
|
||||
|
||||
/-- A download aggregated after the rollup ran: the old chart shows 1 of 2. -/
|
||||
theorem chartOld_drops_late_download : chartOld 1 2 < chartNew 1 2 := by decide
|
||||
|
||||
end Gohoarder.Stats
|
||||
@@ -0,0 +1,96 @@
|
||||
{"version": "1.3.0",
|
||||
"packagesDir": ".lake/packages",
|
||||
"packages":
|
||||
[{"url": "https://github.com/leanprover-community/mathlib4",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||
"name": "mathlib",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "v4.36.0",
|
||||
"inherited": false,
|
||||
"configFile": "lakefile.lean"},
|
||||
{"url": "https://github.com/leanprover-community/plausible",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "054b228ce0ac61d767c6e71ba73a24728f191b72",
|
||||
"name": "plausible",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "main",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"},
|
||||
{"url": "https://github.com/leanprover-community/LeanSearchClient",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9",
|
||||
"name": "LeanSearchClient",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "main",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"},
|
||||
{"url": "https://github.com/leanprover-community/import-graph",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0",
|
||||
"name": "importGraph",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "main",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"},
|
||||
{"url": "https://github.com/leanprover-community/ProofWidgets4",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "2f0f3520daeac2d9310ff25b7a877a0e5cdaa203",
|
||||
"name": "proofwidgets",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "main",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.lean"},
|
||||
{"url": "https://github.com/leanprover-community/aesop",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "66ff77cf0c4c898799e4b94d14db55f7a02d0c5a",
|
||||
"name": "aesop",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "master",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"},
|
||||
{"url": "https://github.com/leanprover-community/quote4",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "ff055a2fcc835935e0ae607339b455a5f5896b4b",
|
||||
"name": "Qq",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "master",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"},
|
||||
{"url": "https://github.com/leanprover-community/batteries",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover-community",
|
||||
"rev": "b4b25a3886a16daacaf6615c2eea7170a6e8f458",
|
||||
"name": "batteries",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "main",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"},
|
||||
{"url": "https://github.com/leanprover/lean4-cli",
|
||||
"type": "git",
|
||||
"subDir": null,
|
||||
"scope": "leanprover",
|
||||
"rev": "50810f72af7618bee62fe9800dc26e806c188703",
|
||||
"name": "Cli",
|
||||
"manifestFile": "lake-manifest.json",
|
||||
"inputRev": "v4.36.0",
|
||||
"inherited": true,
|
||||
"configFile": "lakefile.toml"}],
|
||||
"name": "gohoarder",
|
||||
"lakeDir": ".lake",
|
||||
"fixedToolchain": false}
|
||||
@@ -0,0 +1,10 @@
|
||||
name = "gohoarder"
|
||||
defaultTargets = ["Gohoarder"]
|
||||
|
||||
[[require]]
|
||||
name = "mathlib"
|
||||
scope = "leanprover-community"
|
||||
rev = "v4.36.0"
|
||||
|
||||
[[lean_lib]]
|
||||
name = "Gohoarder"
|
||||
@@ -0,0 +1 @@
|
||||
leanprover/lean4:v4.36.0
|
||||
@@ -0,0 +1,27 @@
|
||||
import Gohoarder
|
||||
import Lean
|
||||
|
||||
/-! Fails unless every theorem under `Gohoarder` depends only on `propext`, `Classical.choice` and
|
||||
`Quot.sound`. Run from `lean4/`: `lake env lean scripts/Axioms.lean`. -/
|
||||
|
||||
open Lean Elab Command
|
||||
|
||||
elab "#audit_axioms" : command => do
|
||||
let env ← getEnv
|
||||
let allowed : List Name := [``propext, ``Classical.choice, ``Quot.sound]
|
||||
let mut audited : Nat := 0
|
||||
let mut bad : Array String := #[]
|
||||
for (n, ci) in env.constants.map₁.toList do
|
||||
if `Gohoarder |>.isPrefixOf n then
|
||||
if let .thmInfo _ := ci then
|
||||
audited := audited + 1
|
||||
let axs ← liftCoreM (collectAxioms n)
|
||||
for a in axs do
|
||||
if !allowed.contains a then
|
||||
bad := bad.push s!"{n} uses {a}"
|
||||
if bad.isEmpty then
|
||||
logInfo m!"{audited} theorems audited, axioms within {allowed}"
|
||||
else
|
||||
throwError "unexpected axioms:\n{"\n".intercalate bad.toList}"
|
||||
|
||||
#audit_axioms
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/bin/sh
|
||||
# Fails when a Go file cited by the Lean model changed in the range with no change under lean4/.
|
||||
# Usage: lean4/scripts/check_currency.sh [base-ref] (default origin/main)
|
||||
set -eu
|
||||
|
||||
base="${1:-origin/main}"
|
||||
root="$(git rev-parse --show-toplevel)"
|
||||
cd "$root"
|
||||
|
||||
changed="$(git diff --name-only "$base"...HEAD)"
|
||||
cited="$(grep -rhoE '(pkg|cmd)/[A-Za-z0-9_./-]+\.go|Dockerfile\.frontend' lean4/Gohoarder | sort -u)"
|
||||
|
||||
if printf '%s\n' "$changed" | grep -q '^lean4/'; then
|
||||
lean_changed=yes
|
||||
else
|
||||
lean_changed=no
|
||||
fi
|
||||
|
||||
status=0
|
||||
for file in $cited; do
|
||||
if [ ! -f "$file" ]; then
|
||||
echo "MISSING: $file is cited by the Lean model but does not exist"
|
||||
status=1
|
||||
continue
|
||||
fi
|
||||
if printf '%s\n' "$changed" | grep -qx "$file" && [ "$lean_changed" = no ]; then
|
||||
echo "REVIEW: $file is cited by the Lean model and changed with no lean4/ change"
|
||||
status=1
|
||||
fi
|
||||
done
|
||||
|
||||
[ "$status" -eq 0 ] && echo "currency: every cited file exists and none changed without a model change"
|
||||
exit "$status"
|
||||
+15
-6
@@ -233,6 +233,7 @@ func (a *App) initializeComponents() error {
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
})
|
||||
@@ -592,6 +593,19 @@ func (a *App) setupServer() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// startWorkers starts the background loops that live as long as ctx.
|
||||
func (a *App) startWorkers(ctx context.Context) {
|
||||
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
|
||||
a.wsServer.Start(ctx)
|
||||
|
||||
// Start download data aggregation worker (runs every hour)
|
||||
go a.startAggregationWorker(ctx)
|
||||
|
||||
// Start periodic stats broadcaster (every 30s) so connected WS clients
|
||||
// see live counter updates without polling.
|
||||
go a.startStatsBroadcaster(ctx)
|
||||
}
|
||||
|
||||
func (a *App) Run() error {
|
||||
// Cancellable worker context: aggregation + stats broadcaster goroutines
|
||||
// watch ctx.Done() and exit, so Shutdown can stop them before closing
|
||||
@@ -600,12 +614,7 @@ func (a *App) Run() error {
|
||||
a.cancel = cancel
|
||||
defer cancel()
|
||||
|
||||
// Start download data aggregation worker (runs every hour)
|
||||
go a.startAggregationWorker(ctx)
|
||||
|
||||
// Start periodic stats broadcaster (every 30s) so connected WS clients
|
||||
// see live counter updates without polling.
|
||||
go a.startStatsBroadcaster(ctx)
|
||||
a.startWorkers(ctx)
|
||||
|
||||
// Start Fiber server in goroutine. Branch on TLS to pick Listen vs ListenTLS.
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
@@ -407,6 +407,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
"total_downloads": cacheStats.TotalDownloads,
|
||||
"total_size": cacheStats.TotalSize,
|
||||
"max_cache_size": a.config.Cache.MaxSizeBytes,
|
||||
"idle_ttl": int64(a.config.Cache.IdleTTL / time.Second), // seconds, 0 = idle eviction off
|
||||
"cache_hits": cacheStats.TotalDownloads,
|
||||
"cache_misses": 0, // TODO: Track cache misses
|
||||
"cache_evictions": 0, // TODO: Track evictions
|
||||
|
||||
@@ -45,11 +45,15 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
Str("version", version).
|
||||
Msg("Getting vulnerabilities for package")
|
||||
|
||||
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
|
||||
releaseVersion := ""
|
||||
if pkgErr == nil && pkg != nil {
|
||||
releaseVersion = pkg.ReleaseVersion
|
||||
}
|
||||
|
||||
// Get scan result from metadata store
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, registry, name, version)
|
||||
if err != nil {
|
||||
// Check if package exists
|
||||
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
|
||||
if pkgErr != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
@@ -57,9 +61,10 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
// Package exists but not scanned yet
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"package": fiber.Map{
|
||||
"registry": registry,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"registry": registry,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"release_version": releaseVersion,
|
||||
},
|
||||
"scanned": false,
|
||||
"status": "pending",
|
||||
@@ -89,11 +94,15 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
}
|
||||
packageKey := registry + "/" + bypassName + "@" + version
|
||||
packageKeyNoVersion := registry + "/" + bypassName
|
||||
releaseKey := ""
|
||||
if releaseVersion != "" {
|
||||
releaseKey = registry + "/" + bypassName + "@" + releaseVersion
|
||||
}
|
||||
bypassedCVEs := make(map[string]*metadata.CVEBypass)
|
||||
for _, bypass := range bypasses {
|
||||
if bypass.Type == metadata.BypassTypeCVE && bypass.Active {
|
||||
// Check if bypass applies to this package
|
||||
if bypass.AppliesTo == "" || bypass.AppliesTo == packageKey || bypass.AppliesTo == packageKeyNoVersion {
|
||||
if bypass.AppliesTo == "" || bypass.AppliesTo == packageKey || bypass.AppliesTo == packageKeyNoVersion || (releaseKey != "" && bypass.AppliesTo == releaseKey) {
|
||||
bypassedCVEs[strings.ToUpper(bypass.Target)] = bypass
|
||||
}
|
||||
}
|
||||
@@ -141,9 +150,10 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
// Build response
|
||||
response := fiber.Map{
|
||||
"package": fiber.Map{
|
||||
"registry": registry,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"registry": registry,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"release_version": releaseVersion,
|
||||
},
|
||||
"scanned": true,
|
||||
"scanner": scanResult.Scanner,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func TestStatsReportsIdleTTLSeconds(t *testing.T) {
|
||||
for name, tt := range map[string]struct {
|
||||
idle time.Duration
|
||||
want float64
|
||||
}{
|
||||
"a week": {idle: 168 * time.Hour, want: 604800},
|
||||
"disabled": {idle: 0, want: 0},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Cache.IdleTTL = tt.idle })
|
||||
|
||||
code, _, body := doRequest(t, a, "/api/stats", nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("status %d, body %q", code, body)
|
||||
}
|
||||
var resp struct {
|
||||
Stats map[string]any `json:"stats"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &resp); err != nil {
|
||||
t.Fatalf("decode %q: %v", body, err)
|
||||
}
|
||||
got, ok := resp.Stats["idle_ttl"].(float64)
|
||||
if !ok || got != tt.want {
|
||||
t.Errorf("stats.idle_ttl = %v, want %v (body %s)", resp.Stats["idle_ttl"], tt.want, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
|
||||
// event loop: without it the 256-slot broadcast channel fills and every later
|
||||
// event is dropped.
|
||||
func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
|
||||
const events = 1000
|
||||
for i := 0; i < events; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
if i%200 == 0 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
if dropped := a.wsServer.Dropped(); dropped != 0 {
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events)
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -147,7 +147,16 @@ func (f *fakeStore) GetTimeSeriesStats(context.Context, string, string) (*metada
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) AggregateDownloadData(context.Context) error { return metadata.ErrNotImplemented }
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
func (f *fakeStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
|
||||
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
|
||||
func fastCfg() Config { return Config{BcryptCost: bcrypt.MinCost} }
|
||||
|
||||
Vendored
+189
-85
@@ -8,7 +8,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -49,10 +48,9 @@ type Manager struct {
|
||||
sf singleflight.Group
|
||||
config Config
|
||||
cleanupWG sync.WaitGroup
|
||||
mu sync.RWMutex
|
||||
bcMu sync.RWMutex
|
||||
closeOnce sync.Once
|
||||
evicting bool
|
||||
evictMu sync.Mutex // serialises LRU eviction; a second caller waits and re-checks its quota
|
||||
}
|
||||
|
||||
// SetBroadcaster wires an events.Broadcaster onto the manager so cache
|
||||
@@ -81,17 +79,31 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
|
||||
|
||||
// Config holds cache manager configuration
|
||||
type Config struct {
|
||||
DefaultTTL time.Duration // Default TTL for cached packages
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
DefaultTTL time.Duration // Freshness TTL for metadata entries
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
|
||||
// cleanupBatchSize bounds how many rows one cleanup query reads.
|
||||
const cleanupBatchSize = metadata.DefaultBatchSize
|
||||
|
||||
// getAttempts bounds how often Get re-resolves an entry whose blob vanished.
|
||||
const getAttempts = 2
|
||||
|
||||
// Eviction metric reasons.
|
||||
const (
|
||||
evictReasonTTL = "ttl"
|
||||
evictReasonIdle = "idle"
|
||||
)
|
||||
|
||||
// scannerToggle is implemented by scanners that can be switched off.
|
||||
type scannerToggle interface {
|
||||
Enabled() bool
|
||||
@@ -155,6 +167,10 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
log.Info().Msg("Cache manager initialized with analytics tracking enabled")
|
||||
}
|
||||
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
|
||||
if config.DefaultTTL == 0 {
|
||||
config.DefaultTTL = 7 * 24 * time.Hour // 7 days default
|
||||
}
|
||||
@@ -191,6 +207,9 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
// Rows cached before idle eviction existed carry an age-based expiry.
|
||||
manager.clearArtifactExpiry(bgCtx)
|
||||
|
||||
// Start background cleanup worker
|
||||
manager.cleanupWG.Add(1)
|
||||
go manager.cleanupWorker()
|
||||
@@ -203,36 +222,44 @@ func (m *Manager) Get(ctx context.Context, registry, name, version string, fetch
|
||||
// Use singleflight to deduplicate concurrent requests
|
||||
key := fmt.Sprintf("%s/%s/%s", registry, name, version)
|
||||
|
||||
result, err, _ := m.sf.Do(key, func() (interface{}, error) {
|
||||
// getOrFetch returns a CacheEntry with Data == nil. Each caller
|
||||
// re-opens its own storage reader below to avoid sharing a
|
||||
// single io.ReadCloser across concurrent waiters.
|
||||
return m.getOrFetch(ctx, registry, name, version, fetchFunc)
|
||||
})
|
||||
var openErr error
|
||||
// A purge can delete the blob between the cache-hit probe and the open
|
||||
// below. The second pass sees the miss and fetches again.
|
||||
for attempt := 0; attempt < getAttempts; attempt++ {
|
||||
result, err, _ := m.sf.Do(key, func() (interface{}, error) {
|
||||
// getOrFetch returns a CacheEntry with Data == nil. Each caller
|
||||
// re-opens its own storage reader below to avoid sharing a
|
||||
// single io.ReadCloser across concurrent waiters.
|
||||
return m.getOrFetch(ctx, registry, name, version, fetchFunc)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entry := result.(*CacheEntry)
|
||||
if entry == nil || entry.Package == nil {
|
||||
return nil, errors.New(errors.ErrCodeStorageFailure, "cache entry missing package metadata")
|
||||
}
|
||||
|
||||
// Open a fresh ReadCloser per caller from storage.
|
||||
data, err := m.storage.Get(ctx, entry.Package.StorageKey)
|
||||
if err != nil {
|
||||
openErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
// Return a copy so concurrent waiters don't share the Data field.
|
||||
return &CacheEntry{
|
||||
Data: data,
|
||||
Package: entry.Package,
|
||||
UpstreamURL: entry.UpstreamURL,
|
||||
CacheControl: entry.CacheControl,
|
||||
FromCache: entry.FromCache,
|
||||
}, nil
|
||||
}
|
||||
|
||||
entry := result.(*CacheEntry)
|
||||
if entry == nil || entry.Package == nil {
|
||||
return nil, errors.New(errors.ErrCodeStorageFailure, "cache entry missing package metadata")
|
||||
}
|
||||
|
||||
// Open a fresh ReadCloser per caller from storage.
|
||||
data, err := m.storage.Get(ctx, entry.Package.StorageKey)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to retrieve cached package")
|
||||
}
|
||||
|
||||
// Return a copy so concurrent waiters don't share the Data field.
|
||||
return &CacheEntry{
|
||||
Data: data,
|
||||
Package: entry.Package,
|
||||
UpstreamURL: entry.UpstreamURL,
|
||||
CacheControl: entry.CacheControl,
|
||||
FromCache: entry.FromCache,
|
||||
}, nil
|
||||
return nil, errors.Wrap(openErr, errors.ErrCodeStorageFailure, "failed to retrieve cached package")
|
||||
}
|
||||
|
||||
// getOrFetch implements the actual get-or-fetch logic
|
||||
@@ -241,9 +268,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err == nil {
|
||||
// Package found in metadata, check if expired
|
||||
if pkg.ExpiresAt != nil && time.Now().After(*pkg.ExpiresAt) {
|
||||
if pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt) {
|
||||
log.Debug().Str("package", name).Str("version", version).Msg("Package expired, re-fetching")
|
||||
metrics.RecordCacheEviction("ttl")
|
||||
metrics.RecordCacheEviction(evictReasonTTL)
|
||||
// Delete expired package
|
||||
_ = m.deletePackage(ctx, pkg) // #nosec G104 -- Async cleanup
|
||||
} else {
|
||||
@@ -297,8 +324,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
// entries (index pages, lists, .mod/.info) are not scannable
|
||||
// packages, so skip them to avoid a bogus "clean" verdict and
|
||||
// the extra database round-trip.
|
||||
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
|
||||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
if m.scanner != nil && !isMetadataEntry {
|
||||
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
|
||||
if vulnErr != nil {
|
||||
@@ -313,12 +339,12 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
// underlying transport is non-blocking. Only emitted on
|
||||
// the cache-hit path — the miss-then-fetch path is
|
||||
// covered by EventPackageCached emitted from store().
|
||||
m.emit(string(websocket.EventPackageDownloaded), map[string]interface{}{
|
||||
m.emit(string(websocket.EventPackageDownloaded), withReleaseVersion(map[string]interface{}{
|
||||
"registry": registry,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"cache_hit": true,
|
||||
})
|
||||
}, pkg.ReleaseVersion))
|
||||
|
||||
// Data is intentionally nil; Get() opens a fresh reader per caller.
|
||||
return &CacheEntry{
|
||||
@@ -366,8 +392,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
|
||||
// Skip security scan wait for metadata entries (index pages, lists, etc.)
|
||||
// Also skip Go module metadata files (.mod, .info)
|
||||
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
|
||||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
|
||||
// Wait briefly for initial scan to complete if scanner is enabled
|
||||
// This prevents serving vulnerable packages on first request.
|
||||
@@ -553,8 +578,16 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
_ = tempFile.Close() // #nosec G104 -- cleanup; scan may still read the file
|
||||
|
||||
// Create metadata entry
|
||||
now := time.Now()
|
||||
expiresAt := now.Add(m.config.DefaultTTL)
|
||||
now := m.now()
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
|
||||
// Artifacts are immutable, so only idle eviction removes them; metadata
|
||||
// entries must refresh and keep a freshness expiry.
|
||||
var expiresAt *time.Time
|
||||
if isMetadataEntry {
|
||||
exp := now.Add(m.config.DefaultTTL)
|
||||
expiresAt = &exp
|
||||
}
|
||||
|
||||
pkg := &metadata.Package{
|
||||
ID: uuid.New().String(),
|
||||
@@ -570,7 +603,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
AuthProvider: authProvider,
|
||||
CachedAt: now,
|
||||
LastAccessed: now,
|
||||
ExpiresAt: &expiresAt,
|
||||
ExpiresAt: expiresAt,
|
||||
DownloadCount: 0,
|
||||
Metadata: make(map[string]string),
|
||||
}
|
||||
@@ -583,8 +616,6 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
// TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed
|
||||
// based on upstream Cache-Control. Plumbing per-response TTL from registry handlers
|
||||
// is out of scope here and tracked separately.
|
||||
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
|
||||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
|
||||
if err := m.metadata.SavePackage(ctx, pkg); err != nil {
|
||||
// Clean up storage if metadata save fails
|
||||
_ = m.storage.Delete(ctx, storageKey) // #nosec G104 -- Cleanup, error logged
|
||||
@@ -602,13 +633,13 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
scanStatus = "pending"
|
||||
}
|
||||
}
|
||||
m.emit(string(websocket.EventPackageCached), map[string]interface{}{
|
||||
m.emit(string(websocket.EventPackageCached), withReleaseVersion(map[string]interface{}{
|
||||
"registry": registry,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"size": size,
|
||||
"scan_status": scanStatus,
|
||||
})
|
||||
}, releaseVersion))
|
||||
|
||||
// Scan package if scanner is enabled (run in background to not block cache operations)
|
||||
// Skip scanning metadata entries (index pages, lists, etc.)
|
||||
@@ -685,19 +716,8 @@ func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) erro
|
||||
|
||||
// evict implements LRU eviction
|
||||
func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
m.mu.Lock()
|
||||
if m.evicting {
|
||||
m.mu.Unlock()
|
||||
return errors.New(errors.ErrCodeStorageFailure, "eviction already in progress")
|
||||
}
|
||||
m.evicting = true
|
||||
m.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
m.mu.Lock()
|
||||
m.evicting = false
|
||||
m.mu.Unlock()
|
||||
}()
|
||||
m.evictMu.Lock()
|
||||
defer m.evictMu.Unlock()
|
||||
|
||||
log.Info().Int64("needed", needed).Msg("Starting LRU eviction")
|
||||
|
||||
@@ -715,12 +735,14 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
break
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
for _, pkg := range packages {
|
||||
if err := m.deletePackage(ctx, pkg); err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to evict package")
|
||||
continue
|
||||
}
|
||||
|
||||
deleted++
|
||||
freed += pkg.Size
|
||||
metrics.RecordCacheEviction("lru")
|
||||
|
||||
@@ -729,8 +751,8 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
}
|
||||
}
|
||||
|
||||
if len(packages) < opts.Limit {
|
||||
break // No more packages
|
||||
if len(packages) < opts.Limit || deleted == 0 {
|
||||
break // No more packages, or the same rows would be listed again
|
||||
}
|
||||
}
|
||||
|
||||
@@ -738,7 +760,7 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanupWorker runs periodic cleanup of expired packages.
|
||||
// cleanupWorker runs periodic cleanup of expired and idle packages.
|
||||
// Exits when stopCh is closed (via Close()).
|
||||
func (m *Manager) cleanupWorker() {
|
||||
defer m.cleanupWG.Done()
|
||||
@@ -751,39 +773,113 @@ func (m *Manager) cleanupWorker() {
|
||||
case <-m.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
ctx := context.Background()
|
||||
m.cleanup(ctx)
|
||||
m.cleanup(m.bgCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cleanup removes expired packages
|
||||
func (m *Manager) cleanup(ctx context.Context) {
|
||||
log.Debug().Msg("Starting cleanup worker")
|
||||
func (m *Manager) now() time.Time {
|
||||
return m.config.Now()
|
||||
}
|
||||
|
||||
// List all packages
|
||||
packages, err := m.metadata.ListPackages(ctx, &metadata.ListOptions{})
|
||||
// clearArtifactExpiry drops the age-based expiry that older versions set on artifacts.
|
||||
func (m *Manager) clearArtifactExpiry(ctx context.Context) {
|
||||
cleared, err := m.metadata.ClearArtifactExpiry(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages for cleanup")
|
||||
log.Error().Err(err).Msg("Failed to clear artifact expiry")
|
||||
return
|
||||
}
|
||||
if cleared > 0 {
|
||||
log.Info().Int64("count", cleared).Msg("Cleared age-based expiry from cached artifacts")
|
||||
}
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var cleaned int
|
||||
// purgeResult totals the packages one purge pass removed.
|
||||
type purgeResult struct {
|
||||
bytes int64
|
||||
count int
|
||||
}
|
||||
|
||||
for _, pkg := range packages {
|
||||
if pkg.ExpiresAt != nil && now.After(*pkg.ExpiresAt) {
|
||||
if err := m.deletePackage(ctx, pkg); err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to clean up expired package")
|
||||
// purge deletes packages in bounded batches until the list query runs dry.
|
||||
// stillDue re-checks each package just before deletion so one requested after
|
||||
// the batch was read is kept.
|
||||
func (m *Manager) purge(
|
||||
ctx context.Context,
|
||||
reason string,
|
||||
list func(limit int) ([]*metadata.Package, error),
|
||||
stillDue func(*metadata.Package) bool,
|
||||
) purgeResult {
|
||||
var res purgeResult
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
for ctx.Err() == nil {
|
||||
batch, err := list(cleanupBatchSize)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("reason", reason).Msg("Failed to list packages for cleanup")
|
||||
return res
|
||||
}
|
||||
|
||||
unseen := 0
|
||||
for _, pkg := range batch {
|
||||
key := m.generateStorageKey(pkg.Registry, pkg.Name, pkg.Version)
|
||||
if _, dup := seen[key]; dup {
|
||||
continue
|
||||
}
|
||||
cleaned++
|
||||
seen[key] = struct{}{}
|
||||
unseen++
|
||||
|
||||
current, err := m.metadata.GetPackage(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if err != nil || current == nil || !stillDue(current) {
|
||||
continue
|
||||
}
|
||||
if err := m.deletePackage(ctx, current); err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Str("reason", reason).Msg("Failed to clean up package")
|
||||
continue
|
||||
}
|
||||
res.count++
|
||||
res.bytes += current.Size
|
||||
metrics.RecordCacheEviction(reason)
|
||||
}
|
||||
|
||||
// A short batch is the last one; a batch of only repeats means every
|
||||
// remaining row failed to delete.
|
||||
if len(batch) < cleanupBatchSize || unseen == 0 {
|
||||
return res
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
if cleaned > 0 {
|
||||
log.Info().Int("count", cleaned).Msg("Cleanup completed")
|
||||
// cleanup removes metadata entries past their freshness expiry and, when
|
||||
// IdleTTL is set, every package not requested within IdleTTL.
|
||||
func (m *Manager) cleanup(ctx context.Context) {
|
||||
start := m.now()
|
||||
log.Debug().Msg("Starting cleanup worker")
|
||||
|
||||
m.clearArtifactExpiry(ctx)
|
||||
|
||||
expired := m.purge(ctx, evictReasonTTL,
|
||||
func(limit int) ([]*metadata.Package, error) {
|
||||
return m.metadata.ListExpiredPackages(ctx, start, limit)
|
||||
},
|
||||
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(start) })
|
||||
|
||||
var idle purgeResult
|
||||
if m.config.IdleTTL > 0 {
|
||||
cutoff := start.Add(-m.config.IdleTTL)
|
||||
idle = m.purge(ctx, evictReasonIdle,
|
||||
func(limit int) ([]*metadata.Package, error) {
|
||||
return m.metadata.ListIdlePackages(ctx, cutoff, limit)
|
||||
},
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Int("expired", expired.count).
|
||||
Int("idle", idle.count).
|
||||
Int64("bytes_freed", expired.bytes+idle.bytes).
|
||||
Dur("idle_ttl", m.config.IdleTTL).
|
||||
Msg("Cleanup completed")
|
||||
}
|
||||
|
||||
// generateStorageKey generates a storage key for a package
|
||||
@@ -853,3 +949,11 @@ func (m *Manager) Close() error {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// withReleaseVersion adds release_version to an event payload when the cache key is not a release version.
|
||||
func withReleaseVersion(payload map[string]interface{}, releaseVersion string) map[string]interface{} {
|
||||
if releaseVersion != "" {
|
||||
payload["release_version"] = releaseVersion
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
Vendored
+11
@@ -230,6 +230,17 @@ func (m *MockMetadataStore) AggregateDownloadData(ctx context.Context) error {
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
// The idle-eviction queries are not mocked per test: no expiry, no idle rows.
|
||||
func (m *MockMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
|
||||
// API key methods are not used by the cache package; stub them out so the
|
||||
// mock continues to satisfy metadata.MetadataStore after the interface gained
|
||||
// API key persistence methods.
|
||||
|
||||
Vendored
+398
@@ -0,0 +1,398 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func evictions(c prometheus.Counter) float64 {
|
||||
var m dto.Metric
|
||||
if err := c.Write(&m); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return m.GetCounter().GetValue()
|
||||
}
|
||||
|
||||
type fakeClock struct {
|
||||
now time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newFakeClock() *fakeClock {
|
||||
return &fakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
|
||||
}
|
||||
|
||||
func (c *fakeClock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
|
||||
func (c *fakeClock) Advance(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.now = c.now.Add(d)
|
||||
}
|
||||
|
||||
type memStorage struct {
|
||||
storage.StorageBackend
|
||||
objects map[string][]byte
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newMemStorage() *memStorage { return &memStorage{objects: map[string][]byte{}} }
|
||||
|
||||
func (s *memStorage) Get(_ context.Context, key string) (io.ReadCloser, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
b, ok := s.objects[key]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(b)), nil
|
||||
}
|
||||
|
||||
func (s *memStorage) Put(_ context.Context, key string, data io.Reader, _ *storage.PutOptions) error {
|
||||
b, err := io.ReadAll(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.objects[key] = b
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStorage) Delete(_ context.Context, key string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStorage) GetQuota(context.Context) (*storage.QuotaInfo, error) {
|
||||
return &storage.QuotaInfo{}, nil
|
||||
}
|
||||
|
||||
func (s *memStorage) Close() error { return nil }
|
||||
|
||||
func (s *memStorage) has(key string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.objects[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// memMetadata mirrors the real store's contract: UpdateDownloadCount stamps
|
||||
// last_accessed, and the list queries are ordered and bounded.
|
||||
type memMetadata struct {
|
||||
metadata.MetadataStore
|
||||
clock *fakeClock
|
||||
pkgs map[string]*metadata.Package
|
||||
onList func()
|
||||
maxLimit int
|
||||
mu sync.Mutex
|
||||
idleCalls int
|
||||
}
|
||||
|
||||
func newMemMetadata(clock *fakeClock) *memMetadata {
|
||||
return &memMetadata{clock: clock, pkgs: map[string]*metadata.Package{}}
|
||||
}
|
||||
|
||||
func pkgKey(registry, name, version string) string { return registry + "/" + name + "/" + version }
|
||||
|
||||
func (m *memMetadata) SavePackage(_ context.Context, pkg *metadata.Package) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cp := *pkg
|
||||
m.pkgs[pkgKey(pkg.Registry, pkg.Name, pkg.Version)] = &cp
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) GetPackage(_ context.Context, registry, name, version string) (*metadata.Package, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
p, ok := m.pkgs[pkgKey(registry, name, version)]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
cp := *p
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) DeletePackage(_ context.Context, registry, name, version string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.pkgs, pkgKey(registry, name, version))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) UpdateDownloadCount(_ context.Context, registry, name, version string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
p, ok := m.pkgs[pkgKey(registry, name, version)]
|
||||
if !ok {
|
||||
return errors.New("not found")
|
||||
}
|
||||
p.DownloadCount++
|
||||
p.LastAccessed = m.clock.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) list(limit int, match func(*metadata.Package) bool, less func(a, b *metadata.Package) bool) []*metadata.Package {
|
||||
m.mu.Lock()
|
||||
if limit > m.maxLimit {
|
||||
m.maxLimit = limit
|
||||
}
|
||||
var out []*metadata.Package
|
||||
for _, p := range m.pkgs {
|
||||
if match(p) {
|
||||
cp := *p
|
||||
out = append(out, &cp)
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
sort.Slice(out, func(i, j int) bool { return less(out[i], out[j]) })
|
||||
if limit > 0 && len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
if m.onList != nil {
|
||||
m.onList()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *memMetadata) ListIdlePackages(_ context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
m.mu.Lock()
|
||||
m.idleCalls++
|
||||
m.mu.Unlock()
|
||||
return m.list(limit,
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
|
||||
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) ListExpiredPackages(_ context.Context, before time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return m.list(limit,
|
||||
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(before) },
|
||||
func(a, b *metadata.Package) bool { return a.ExpiresAt.Before(*b.ExpiresAt) }), nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
var n int64
|
||||
for _, p := range m.pkgs {
|
||||
if p.ExpiresAt != nil && !metadata.IsMetadataEntry(p.Registry, p.Name, p.Version) {
|
||||
p.ExpiresAt = nil
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) Close() error { return nil }
|
||||
|
||||
func (m *memMetadata) count() int {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return len(m.pkgs)
|
||||
}
|
||||
|
||||
type idleHarness struct {
|
||||
mgr *Manager
|
||||
clock *fakeClock
|
||||
meta *memMetadata
|
||||
store *memStorage
|
||||
fetches int
|
||||
}
|
||||
|
||||
func newIdleHarness(t *testing.T, cfg Config) *idleHarness {
|
||||
t.Helper()
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
h.meta = newMemMetadata(h.clock)
|
||||
cfg.Now = h.clock.Now
|
||||
if cfg.CleanupInterval == 0 {
|
||||
cfg.CleanupInterval = 24 * time.Hour
|
||||
}
|
||||
return h.start(t, cfg)
|
||||
}
|
||||
|
||||
func (h *idleHarness) start(t *testing.T, cfg Config) *idleHarness {
|
||||
t.Helper()
|
||||
mgr, err := New(h.store, h.meta, nil, nil, cfg)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
h.mgr = mgr
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *idleHarness) get(t *testing.T, name, version string) *CacheEntry {
|
||||
t.Helper()
|
||||
entry, err := h.mgr.Get(context.Background(), "npm", name, version, func(context.Context) (*FetchResult, error) {
|
||||
h.fetches++
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
return entry
|
||||
}
|
||||
|
||||
func (h *idleHarness) exists(name, version string) bool {
|
||||
_, err := h.meta.GetPackage(context.Background(), "npm", name, version)
|
||||
return err == nil && h.store.has(fmt.Sprintf("npm/%s/%s", name, version))
|
||||
}
|
||||
|
||||
const (
|
||||
day = 24 * time.Hour
|
||||
artifactVer = "4.17.21"
|
||||
)
|
||||
|
||||
func TestIdleTTL_AccessedArtifactSurvivesDefaultTTL(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
|
||||
entry := h.get(t, "lodash", artifactVer)
|
||||
require.Nil(t, entry.Package.ExpiresAt, "an artifact is immutable: no age-based expiry")
|
||||
|
||||
h.clock.Advance(2 * day)
|
||||
h.get(t, "lodash", artifactVer) // touches last_accessed
|
||||
h.clock.Advance(2 * day) // 4 days after caching, past DefaultTTL; idle for only 2
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.True(t, h.exists("lodash", artifactVer))
|
||||
h.get(t, "lodash", artifactVer)
|
||||
require.Equal(t, 1, h.fetches, "served from cache, not re-fetched")
|
||||
}
|
||||
|
||||
func TestIdleTTL_IdleArtifactIsDeletedFromStorageAndMetadata(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.get(t, "left-pad", "1.3.0")
|
||||
h.clock.Advance(2 * day)
|
||||
h.get(t, "left-pad", "1.3.0") // keeps left-pad alive
|
||||
h.clock.Advance(2 * day) // lodash idle for 4 days
|
||||
|
||||
before := evictions(metrics.CacheEvictions.WithLabelValues("idle"))
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.False(t, h.exists("lodash", artifactVer))
|
||||
require.False(t, h.store.has("npm/lodash/"+artifactVer), "storage object removed")
|
||||
_, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
|
||||
require.Error(t, err, "metadata row removed")
|
||||
require.True(t, h.exists("left-pad", "1.3.0"))
|
||||
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("idle")))
|
||||
}
|
||||
|
||||
func TestIdleTTL_IdleMetadataEntryIsDeleted(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: 3 * day})
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.clock.Advance(4 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.False(t, h.exists("lodash", "metadata"))
|
||||
}
|
||||
|
||||
func TestIdleTTL_MetadataEntryPastFreshnessTTLIsRefetched(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 7 * day})
|
||||
entry := h.get(t, "lodash", "metadata")
|
||||
require.NotNil(t, entry.Package.ExpiresAt)
|
||||
require.Equal(t, h.clock.Now().Add(time.Hour), *entry.Package.ExpiresAt)
|
||||
|
||||
h.clock.Advance(30 * time.Minute)
|
||||
h.get(t, "lodash", "metadata")
|
||||
require.Equal(t, 1, h.fetches, "still fresh")
|
||||
|
||||
h.clock.Advance(2 * time.Hour) // recently requested, but stale
|
||||
before := evictions(metrics.CacheEvictions.WithLabelValues("ttl"))
|
||||
h.get(t, "lodash", "metadata")
|
||||
require.Equal(t, 2, h.fetches, "stale metadata is re-fetched")
|
||||
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("ttl")))
|
||||
}
|
||||
|
||||
func TestIdleTTL_CleanupRemovesExpiredMetadataOnly(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 30 * day})
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.clock.Advance(2 * time.Hour)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.False(t, h.exists("lodash", "metadata"), "past its freshness expiry")
|
||||
require.True(t, h.exists("lodash", artifactVer), "artifacts have no age-based expiry")
|
||||
}
|
||||
|
||||
func TestIdleTTL_ZeroDisablesIdleEviction(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 0})
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.clock.Advance(365 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.True(t, h.exists("lodash", artifactVer))
|
||||
require.Zero(t, h.meta.idleCalls, "no idle query when disabled")
|
||||
}
|
||||
|
||||
func TestIdleTTL_CleanupReadsBoundedBatches(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: day, IdleTTL: day})
|
||||
const total = 1250
|
||||
for i := 0; i < total; i++ {
|
||||
name := fmt.Sprintf("pkg-%d", i)
|
||||
h.get(t, name, "1.0.0")
|
||||
}
|
||||
h.clock.Advance(2 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Zero(t, h.meta.count(), "every idle item removed across batches")
|
||||
require.Positive(t, h.meta.maxLimit)
|
||||
require.LessOrEqual(t, h.meta.maxLimit, cleanupBatchSize, "never loads more than one batch")
|
||||
require.Zero(t, len(h.store.objects))
|
||||
}
|
||||
|
||||
func TestIdleTTL_ItemRequestedDuringCleanupSurvives(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: day})
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.clock.Advance(2 * day)
|
||||
h.meta.onList = func() {
|
||||
h.meta.onList = nil
|
||||
require.NoError(t, h.meta.UpdateDownloadCount(context.Background(), "npm", "lodash", artifactVer))
|
||||
}
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.True(t, h.exists("lodash", artifactVer), "a request between listing and deleting wins")
|
||||
}
|
||||
|
||||
func TestIdleTTL_StartupClearsLegacyArtifactExpiry(t *testing.T) {
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
h.meta = newMemMetadata(h.clock)
|
||||
past := h.clock.Now().Add(-day)
|
||||
require.NoError(t, h.meta.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: "lodash", Version: artifactVer, StorageKey: "npm/lodash/" + artifactVer,
|
||||
LastAccessed: h.clock.Now(), ExpiresAt: &past,
|
||||
}))
|
||||
require.NoError(t, h.store.Put(context.Background(), "npm/lodash/"+artifactVer, strings.NewReader("x"), nil))
|
||||
|
||||
h.start(t, Config{DefaultTTL: 7 * day, IdleTTL: 7 * day, Now: h.clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
|
||||
h.get(t, "lodash", artifactVer)
|
||||
require.Zero(t, h.fetches, "the legacy 7-day expiry no longer evicts a popular artifact")
|
||||
p, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, p.ExpiresAt)
|
||||
}
|
||||
Vendored
+104
@@ -0,0 +1,104 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// evictMeta adds the LRU list and a switchable delete failure to memMetadata.
|
||||
type evictMeta struct {
|
||||
*memMetadata
|
||||
listGate chan struct{}
|
||||
listing chan struct{}
|
||||
failDelete atomic.Bool
|
||||
}
|
||||
|
||||
func (m *evictMeta) ListPackages(_ context.Context, opts *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
if m.listing != nil {
|
||||
select {
|
||||
case m.listing <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-m.listGate
|
||||
}
|
||||
return m.list(opts.Limit,
|
||||
func(*metadata.Package) bool { return true },
|
||||
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
|
||||
}
|
||||
|
||||
func (m *evictMeta) DeletePackage(ctx context.Context, registry, name, version string) error {
|
||||
if m.failDelete.Load() {
|
||||
return errors.New("db down")
|
||||
}
|
||||
return m.memMetadata.DeletePackage(ctx, registry, name, version)
|
||||
}
|
||||
|
||||
func seedPackages(t *testing.T, m *memMetadata, store *memStorage, n int, size int64) {
|
||||
t.Helper()
|
||||
for i := 0; i < n; i++ {
|
||||
name := "pkg" + strings.Repeat("x", i%7) + string(rune('a'+i%26)) + time.Duration(i).String()
|
||||
key := "npm/" + name + "/1.0.0"
|
||||
require.NoError(t, store.Put(context.Background(), key, strings.NewReader("d"), nil))
|
||||
require.NoError(t, m.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: key, Size: size,
|
||||
LastAccessed: m.clock.Now().Add(time.Duration(i) * time.Second),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// evict must return when no package can be deleted instead of re-listing the same rows forever.
|
||||
func TestEvictTerminatesWhenDeletesFail(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage()
|
||||
meta := &evictMeta{memMetadata: newMemMetadata(clock)}
|
||||
seedPackages(t, meta.memMetadata, store, 250, 1)
|
||||
meta.failDelete.Store(true)
|
||||
|
||||
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- mgr.evict(context.Background(), 1000) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
require.NoError(t, err)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("evict did not terminate with failing deletes")
|
||||
}
|
||||
}
|
||||
|
||||
// A store that overlaps a running eviction must wait for it, not fail as over quota.
|
||||
func TestEvictWaitsForRunningEviction(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage()
|
||||
meta := &evictMeta{memMetadata: newMemMetadata(clock), listGate: make(chan struct{}), listing: make(chan struct{}, 1)}
|
||||
seedPackages(t, meta.memMetadata, store, 3, 10)
|
||||
|
||||
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); errs[0] = mgr.evict(context.Background(), 10) }()
|
||||
<-meta.listing // first eviction is inside its list query
|
||||
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); errs[1] = mgr.evict(context.Background(), 10) }()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
close(meta.listGate)
|
||||
wg.Wait()
|
||||
|
||||
require.NoError(t, errs[0])
|
||||
require.NoError(t, errs[1])
|
||||
}
|
||||
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// racyStorage deletes the blob and the row when the second Get opens it, as a purge would.
|
||||
type racyStorage struct {
|
||||
*memStorage
|
||||
meta *memMetadata
|
||||
gets atomic.Int32
|
||||
armed atomic.Bool
|
||||
}
|
||||
|
||||
func (s *racyStorage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
if s.armed.Load() && s.gets.Add(1) == 2 {
|
||||
_ = s.Delete(ctx, key)
|
||||
_ = s.meta.DeletePackage(ctx, "npm", "left-pad", "1.0.0")
|
||||
}
|
||||
return s.memStorage.Get(ctx, key)
|
||||
}
|
||||
|
||||
// A purge between the cache-hit probe and the caller's open must not fail the request.
|
||||
func TestGetRecoversFromPurgeBetweenProbeAndOpen(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
meta := newMemMetadata(clock)
|
||||
store := &racyStorage{memStorage: newMemStorage(), meta: meta}
|
||||
|
||||
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
fetch := func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload")), UpstreamURL: "https://upstream/x"}, nil
|
||||
}
|
||||
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.0.0", fetch)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
|
||||
store.armed.Store(true)
|
||||
entry, err = mgr.Get(context.Background(), "npm", "left-pad", "1.0.0", fetch)
|
||||
require.NoError(t, err)
|
||||
body, err := io.ReadAll(entry.Data)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
require.Equal(t, "payload", string(body))
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
package cache
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestWithReleaseVersion(t *testing.T) {
|
||||
with := withReleaseVersion(map[string]interface{}{"version": "six-1.17.0.tar.gz"}, "1.17.0")
|
||||
if with["release_version"] != "1.17.0" || with["version"] != "six-1.17.0.tar.gz" {
|
||||
t.Errorf("payload = %v", with)
|
||||
}
|
||||
if _, ok := withReleaseVersion(map[string]interface{}{"version": "1.3.0"}, "")["release_version"]; ok {
|
||||
t.Error("empty release version must not be sent")
|
||||
}
|
||||
}
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// policyBlocker blocks every package it is asked about.
|
||||
type policyBlocker struct{ checks atomic.Int32 }
|
||||
|
||||
func (s *policyBlocker) ScanPackage(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *policyBlocker) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
|
||||
s.checks.Add(1)
|
||||
return true, "blocked by policy", nil
|
||||
}
|
||||
|
||||
// Only Go's .mod and .info files are exempt from scanning; a package of any
|
||||
// other registry whose name ends in .mod or .info is a real package.
|
||||
func TestCacheHitScansPackagesNamedLikeGoMetadata(t *testing.T) {
|
||||
tests := []struct {
|
||||
registry, name, version string
|
||||
wantBlocked bool
|
||||
}{
|
||||
{"npm", "left.info", "1.0.0", true},
|
||||
{"npm", "left.mod", "1.0.0", true},
|
||||
{"pypi", "foo.info", "foo.info-1.0.tar.gz", true},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.zip", "v1.0.0", true},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.mod", "v1.0.0", false},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.info", "v1.0.0", false},
|
||||
{"npm", "left-pad", "metadata", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.registry+"/"+tt.name, func(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage()
|
||||
meta := newMemMetadata(clock)
|
||||
key := tt.registry + "/" + tt.name + "/" + tt.version
|
||||
require.NoError(t, store.Put(context.Background(), key, strings.NewReader("data"), nil))
|
||||
require.NoError(t, meta.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: tt.registry, Name: tt.name, Version: tt.version, StorageKey: key, Size: 4, LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
scanner := &policyBlocker{}
|
||||
mgr, err := New(store, meta, scanner, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
entry, err := mgr.Get(context.Background(), tt.registry, tt.name, tt.version, nil)
|
||||
if tt.wantBlocked {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, entry.Data)
|
||||
_ = entry.Data.Close()
|
||||
require.Zero(t, scanner.checks.Load(), "metadata entries must not be scanned")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -133,11 +133,15 @@ type MySQLConfig struct {
|
||||
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
|
||||
}
|
||||
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
// CacheConfig contains cache management configuration
|
||||
type CacheConfig struct {
|
||||
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
|
||||
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
|
||||
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
|
||||
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
}
|
||||
@@ -353,6 +357,7 @@ func Default() *Config {
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: 7 * 24 * time.Hour,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
@@ -505,6 +510,9 @@ func (c *Config) Validate() error {
|
||||
if c.Cache.DefaultTTL < 0 {
|
||||
return fmt.Errorf("cache.default_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.IdleTTL < 0 {
|
||||
return fmt.Errorf("cache.idle_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.MaxSizeBytes < 0 {
|
||||
return fmt.Errorf("cache.max_size_bytes cannot be negative")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func loadCacheYAML(t *testing.T, cacheYAML string) (*Config, error) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(cacheYAML), 0600))
|
||||
return Load(path)
|
||||
}
|
||||
|
||||
func TestIdleTTLDefaultsToAWeek(t *testing.T) {
|
||||
require.Equal(t, 168*time.Hour, Default().Cache.IdleTTL)
|
||||
|
||||
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 168*time.Hour, cfg.Cache.IdleTTL, "an unset key keeps the default")
|
||||
}
|
||||
|
||||
func TestIdleTTLParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want time.Duration
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "duration string", yaml: "cache:\n idle_ttl: 72h\n", want: 72 * time.Hour},
|
||||
{name: "zero disables", yaml: "cache:\n idle_ttl: 0\n", want: 0},
|
||||
{name: "quoted zero disables", yaml: "cache:\n idle_ttl: \"0\"\n", want: 0},
|
||||
{name: "quoted duration", yaml: "cache:\n idle_ttl: \"168h\"\n", want: 168 * time.Hour},
|
||||
{name: "negative rejected", yaml: "cache:\n idle_ttl: -1h\n", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg, err := loadCacheYAML(t, tt.yaml)
|
||||
if tt.wantErr {
|
||||
require.ErrorContains(t, err, "cache.idle_ttl")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, cfg.Cache.IdleTTL)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -157,6 +158,63 @@ func (s *Store) ListPackages(ctx context.Context, opts *metadata.ListOptions) ([
|
||||
return packages, nil
|
||||
}
|
||||
|
||||
// filterPackages returns package records (not scan results) matching keep,
|
||||
// ordered by key ascending and capped at limit.
|
||||
func (s *Store) filterPackages(ctx context.Context, limit int, keep func(*metadata.Package) bool, key func(*metadata.Package) time.Time) ([]*metadata.Package, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []*metadata.Package
|
||||
for _, p := range all {
|
||||
if p.Registry != "" && p.Name != "" && keep(p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return key(out[i]).Before(key(out[j])) })
|
||||
if limit <= 0 {
|
||||
limit = metadata.DefaultBatchSize
|
||||
}
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListIdlePackages returns packages last accessed before idleBefore, oldest first.
|
||||
func (s *Store) ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.filterPackages(ctx, limit,
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
|
||||
func(p *metadata.Package) time.Time { return p.LastAccessed })
|
||||
}
|
||||
|
||||
// ListExpiredPackages returns packages whose ExpiresAt is before the given time, oldest first.
|
||||
func (s *Store) ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.filterPackages(ctx, limit,
|
||||
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(expiredBefore) },
|
||||
func(p *metadata.Package) time.Time { return *p.ExpiresAt })
|
||||
}
|
||||
|
||||
// ClearArtifactExpiry removes ExpiresAt from every non-metadata package.
|
||||
func (s *Store) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var cleared int64
|
||||
for _, p := range all {
|
||||
if p.Registry == "" || p.Name == "" || p.ExpiresAt == nil || metadata.IsMetadataEntry(p.Registry, p.Name, p.Version) {
|
||||
continue
|
||||
}
|
||||
p.ExpiresAt = nil
|
||||
if err := s.SavePackage(ctx, p); err != nil {
|
||||
return cleared, err
|
||||
}
|
||||
cleared++
|
||||
}
|
||||
return cleared, nil
|
||||
}
|
||||
|
||||
// DeletePackage deletes package metadata
|
||||
func (s *Store) DeletePackage(ctx context.Context, registry, name, version string) error {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestListIdlePackages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, _ := newStore(t)
|
||||
now := time.Now()
|
||||
for i, p := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
}{{"old-a", 10 * 24 * time.Hour}, {"old-b", 9 * 24 * time.Hour}, {"fresh", time.Hour}} {
|
||||
require.NoError(t, s.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: p.name, Version: "1", LastAccessed: now.Add(-p.age), Size: int64(i),
|
||||
}))
|
||||
}
|
||||
require.NoError(t, s.SaveScanResult(ctx, &metadata.ScanResult{Registry: "npm", PackageName: "old-a", PackageVersion: "1"}))
|
||||
|
||||
got, err := s.ListIdlePackages(ctx, now.Add(-7*24*time.Hour), 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
require.Equal(t, "old-a", got[0].Name, "oldest first, scan results are not packages")
|
||||
|
||||
got, err = s.ListIdlePackages(ctx, now.Add(-7*24*time.Hour), 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
}
|
||||
|
||||
func TestListExpiredPackagesAndClearArtifactExpiry(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, _ := newStore(t)
|
||||
past := time.Now().Add(-time.Hour)
|
||||
for _, v := range []string{"list", "1.0.0"} {
|
||||
require.NoError(t, s.SavePackage(ctx, &metadata.Package{Registry: "npm", Name: "x", Version: v, ExpiresAt: &past}))
|
||||
}
|
||||
|
||||
cleared, err := s.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), cleared)
|
||||
|
||||
got, err := s.ListExpiredPackages(ctx, time.Now(), 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
require.Equal(t, "list", got[0].Version)
|
||||
}
|
||||
@@ -7,11 +7,16 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// rollupDays is how many completed days each daily pass recomputes; it must stay
|
||||
// below the hourly retention of 7 days.
|
||||
const rollupDays = 6
|
||||
|
||||
// AggregationWorker handles background aggregation of download statistics
|
||||
type AggregationWorker struct {
|
||||
db *gorm.DB
|
||||
stopChan chan struct{}
|
||||
ticker *time.Ticker
|
||||
now func() time.Time // nil means time.Now
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -23,6 +28,14 @@ func NewAggregationWorker(db *gorm.DB) *AggregationWorker {
|
||||
}
|
||||
}
|
||||
|
||||
// clock returns the worker's current time.
|
||||
func (w *AggregationWorker) clock() time.Time {
|
||||
if w.now != nil {
|
||||
return w.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -69,7 +82,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
dialectName := w.db.Name()
|
||||
|
||||
// Calculate cutoff time (aggregate events older than 5 minutes to avoid partial data)
|
||||
cutoff := time.Now().Add(-5 * time.Minute).Truncate(time.Hour)
|
||||
cutoff := w.clock().Add(-5 * time.Minute).Truncate(time.Hour)
|
||||
|
||||
return w.db.Transaction(func(tx *gorm.DB) error {
|
||||
var aggregateSQL string
|
||||
@@ -245,9 +258,11 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
dialectName := w.db.Name()
|
||||
|
||||
// Aggregate yesterday's data
|
||||
yesterday := time.Now().AddDate(0, 0, -1).Truncate(24 * time.Hour)
|
||||
dayEnd := yesterday.Add(24 * time.Hour)
|
||||
// Roll up every completed day whose hourly rows are still held. A pass that
|
||||
// ran before its last hour was aggregated, or never ran, is repaired by the
|
||||
// next one; the hourly rows are kept for longer than rollupDays.
|
||||
dayEnd := w.clock().UTC().Truncate(24 * time.Hour)
|
||||
firstDay := dayEnd.Add(-rollupDays * 24 * time.Hour)
|
||||
|
||||
return w.db.Transaction(func(tx *gorm.DB) error {
|
||||
var aggregateSQL string
|
||||
@@ -319,12 +334,12 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
`
|
||||
}
|
||||
|
||||
if err := tx.Exec(aggregateSQL, yesterday, dayEnd).Error; err != nil {
|
||||
if err := tx.Exec(aggregateSQL, firstDay, dayEnd).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete old hourly stats (keep last 7 days)
|
||||
deleteOlder := time.Now().AddDate(0, 0, -7)
|
||||
deleteOlder := w.clock().AddDate(0, 0, -7)
|
||||
deleteResult := tx.Exec("DELETE FROM download_stats_hourly WHERE time_bucket < ?", deleteOlder)
|
||||
if deleteResult.Error != nil {
|
||||
return deleteResult.Error
|
||||
|
||||
@@ -24,7 +24,8 @@ type GORMStoreV2 struct {
|
||||
registryCache map[string]int32 // Cache registry name -> ID mapping
|
||||
aggregationWorker *AggregationWorker
|
||||
partitionManager *PartitionManager
|
||||
registryCacheMu sync.RWMutex // Protects registryCache for concurrent access
|
||||
now func() time.Time // nil means time.Now
|
||||
registryCacheMu sync.RWMutex // Protects registryCache for concurrent access
|
||||
}
|
||||
|
||||
// NewV2 creates a new GORM-based metadata store with V2 schema
|
||||
@@ -490,7 +491,11 @@ func (s *GORMStoreV2) ListPackages(ctx context.Context, opts *metadata.ListOptio
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
|
||||
}
|
||||
|
||||
// Convert to metadata.Package
|
||||
return s.modelsToPackages(models), nil
|
||||
}
|
||||
|
||||
// modelsToPackages converts rows to metadata packages, resolving registry names once.
|
||||
func (s *GORMStoreV2) modelsToPackages(models []PackageModel) []*metadata.Package {
|
||||
packages := make([]*metadata.Package, len(models))
|
||||
// Snapshot id->name mapping under read lock once to avoid repeated locking
|
||||
s.registryCacheMu.RLock()
|
||||
@@ -502,8 +507,53 @@ func (s *GORMStoreV2) ListPackages(ctx context.Context, opts *metadata.ListOptio
|
||||
for i, model := range models {
|
||||
packages[i] = s.modelToPackage(&model, idToName[model.RegistryID])
|
||||
}
|
||||
return packages
|
||||
}
|
||||
|
||||
return packages, nil
|
||||
// listBatch runs a bounded, index-ordered query over live packages.
|
||||
func (s *GORMStoreV2) listBatch(ctx context.Context, where, order string, arg time.Time, limit int) ([]*metadata.Package, error) {
|
||||
if limit <= 0 {
|
||||
limit = metadata.DefaultBatchSize
|
||||
}
|
||||
var models []PackageModel
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where(where, arg).
|
||||
Order(order).
|
||||
Limit(limit).
|
||||
Find(&models).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
|
||||
}
|
||||
return s.modelsToPackages(models), nil
|
||||
}
|
||||
|
||||
// ListIdlePackages returns live packages last accessed before idleBefore, oldest first.
|
||||
func (s *GORMStoreV2) ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.listBatch(ctx, "last_accessed < ?", "last_accessed ASC", idleBefore, limit)
|
||||
}
|
||||
|
||||
// ListExpiredPackages returns live packages whose expires_at is before the given time, oldest first.
|
||||
func (s *GORMStoreV2) ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.listBatch(ctx, "expires_at < ?", "expires_at ASC", expiredBefore, limit)
|
||||
}
|
||||
|
||||
// ClearArtifactExpiry nulls expires_at on every row that is not a metadata entry.
|
||||
func (s *GORMStoreV2) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
query := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Where("expires_at IS NOT NULL").
|
||||
Where("version NOT IN ?", metadata.MetadataVersions)
|
||||
// The name suffixes mark metadata for Go modules only.
|
||||
suffixConds := make([]string, 0, len(metadata.MetadataNameSuffixes))
|
||||
args := []interface{}{metadata.GoRegistry}
|
||||
for _, suffix := range metadata.MetadataNameSuffixes {
|
||||
suffixConds = append(suffixConds, "name LIKE ?")
|
||||
args = append(args, "%"+suffix)
|
||||
}
|
||||
query = query.Where("NOT (registry_id IN (SELECT id FROM registries WHERE name = ?) AND ("+strings.Join(suffixConds, " OR ")+"))", args...)
|
||||
result := query.UpdateColumn("expires_at", nil)
|
||||
if result.Error != nil {
|
||||
return 0, errors.Wrap(result.Error, errors.ErrCodeStorageFailure, "failed to clear artifact expiry")
|
||||
}
|
||||
return result.RowsAffected, nil
|
||||
}
|
||||
|
||||
// UpdateDownloadCount increments download count and records event
|
||||
@@ -651,6 +701,14 @@ func (s *GORMStoreV2) Close() error {
|
||||
return sqlDB.Close()
|
||||
}
|
||||
|
||||
// clock returns the store's current time.
|
||||
func (s *GORMStoreV2) clock() time.Time {
|
||||
if s.now != nil {
|
||||
return s.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// GetTimeSeriesStats returns time-series download statistics
|
||||
func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, registry string) (*metadata.TimeSeriesStats, error) {
|
||||
stats := &metadata.TimeSeriesStats{
|
||||
@@ -659,7 +717,7 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg
|
||||
DataPoints: make([]*metadata.TimeSeriesDataPoint, 0),
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
now := s.clock().UTC()
|
||||
var span, bucketDuration time.Duration
|
||||
daily := false
|
||||
switch period {
|
||||
@@ -711,13 +769,17 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg
|
||||
}
|
||||
|
||||
if daily {
|
||||
// A completed day's rollup is authoritative over its leftover hourly rows.
|
||||
rollups, err := s.aggregateRows(ctx, "download_stats_daily", since, now, registryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Hourly rows and events only ever undercount a day, so the larger of the
|
||||
// two is the better figure; a rollup alone covers days already trimmed.
|
||||
for _, r := range rollups {
|
||||
counts[r.Timestamp.UTC().Truncate(bucketDuration).Unix()] = r.Value
|
||||
day := r.Timestamp.UTC().Truncate(bucketDuration).Unix()
|
||||
if r.Value > counts[day] {
|
||||
counts[day] = r.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -977,11 +1039,7 @@ func (s *GORMStoreV2) SaveCVEBypass(ctx context.Context, bypass *metadata.CVEByp
|
||||
if bypass.ID != "" {
|
||||
id, err := strconv.ParseInt(bypass.ID, 10, 64)
|
||||
if err == nil {
|
||||
model.ID = id
|
||||
if err := s.db.WithContext(ctx).Save(model).Error; err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to update CVE bypass")
|
||||
}
|
||||
return nil
|
||||
return s.updateCVEBypass(ctx, id, model)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -997,6 +1055,35 @@ func (s *GORMStoreV2) SaveCVEBypass(ctx context.Context, bypass *metadata.CVEByp
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateCVEBypass rewrites the editable columns only, so created_at and usage counters survive an edit.
|
||||
func (s *GORMStoreV2) updateCVEBypass(ctx context.Context, id int64, model *CVEBypassModel) error {
|
||||
db := s.db.WithContext(ctx)
|
||||
res := db.Model(&CVEBypassModel{}).Where("id = ?", id).Updates(map[string]interface{}{
|
||||
"type": model.Type,
|
||||
"target": model.Target,
|
||||
"reason": model.Reason,
|
||||
"created_by": model.CreatedBy,
|
||||
"expires_at": model.ExpiresAt,
|
||||
"notify_on_expiry": model.NotifyOnExpiry,
|
||||
"active": model.Active,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return errors.Wrap(res.Error, errors.ErrCodeStorageFailure, "failed to update CVE bypass")
|
||||
}
|
||||
if res.RowsAffected > 0 {
|
||||
return nil
|
||||
}
|
||||
// MySQL reports 0 rows for an unchanged row, so tell that apart from a missing one.
|
||||
var count int64
|
||||
if err := db.Model(&CVEBypassModel{}).Where("id = ?", id).Count(&count).Error; err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to update CVE bypass")
|
||||
}
|
||||
if count == 0 {
|
||||
return errors.NotFound("CVE bypass not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveCVEBypasses retrieves all active (non-expired) CVE bypasses
|
||||
func (s *GORMStoreV2) GetActiveCVEBypasses(ctx context.Context) ([]*metadata.CVEBypass, error) {
|
||||
var models []CVEBypassModel
|
||||
|
||||
@@ -91,9 +91,20 @@ func (s *MySQLV2IntegrationTestSuite) TearDownTest() {
|
||||
"registries",
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
s.store.db.Exec("TRUNCATE TABLE " + table)
|
||||
}
|
||||
// FOREIGN_KEY_CHECKS is per connection, so truncate on one pinned connection.
|
||||
err := s.store.db.Connection(func(tx *gorm.DB) error {
|
||||
if err := tx.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Exec("SET FOREIGN_KEY_CHECKS = 1")
|
||||
for _, table := range tables {
|
||||
if err := tx.Exec("TRUNCATE TABLE " + table).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
// Re-seed default registries after truncate
|
||||
defaultRegistries := []RegistryModel{
|
||||
@@ -124,10 +135,11 @@ func TestMySQLV2IntegrationTestSuite(t *testing.T) {
|
||||
// Test_MySQLV2_SpecificFeatures tests MySQL-specific features
|
||||
func (s *MySQLV2IntegrationTestSuite) Test_MySQLV2_SpecificFeatures() {
|
||||
// Test that we're actually using MySQL
|
||||
var version string
|
||||
err := s.store.db.Raw("SELECT VERSION()").Scan(&version).Error
|
||||
// VERSION() is a bare number ("8.0.46"); the server flavour is in version_comment.
|
||||
var comment string
|
||||
err := s.store.db.Raw("SELECT @@version_comment").Scan(&comment).Error
|
||||
s.NoError(err)
|
||||
s.Contains(version, "MySQL")
|
||||
s.Contains(comment, "MySQL")
|
||||
}
|
||||
|
||||
// Test_MySQLV2_NoPartitioning tests that partition manager is nil for MySQL
|
||||
|
||||
@@ -713,6 +713,36 @@ func (s *GORMStoreV2TestSuite) Test_V2_SaveCVEBypass_Update() {
|
||||
s.NoError(err)
|
||||
}
|
||||
|
||||
// Test_V2_SaveCVEBypass_UpdateKeepsCreatedAt guards against an edit zeroing created_at.
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_SaveCVEBypass_UpdateKeepsCreatedAt() {
|
||||
bypass := &metadata.CVEBypass{
|
||||
Type: metadata.BypassTypeCVE, Target: "CVE-2024-0003", Reason: "before",
|
||||
CreatedBy: "[email protected]", ExpiresAt: time.Now().Add(time.Hour), Active: true,
|
||||
}
|
||||
s.Require().NoError(s.store.SaveCVEBypass(s.ctx, bypass))
|
||||
|
||||
var before CVEBypassModel
|
||||
s.Require().NoError(s.store.db.First(&before, bypass.ID).Error)
|
||||
|
||||
bypass.Reason = "after"
|
||||
s.Require().NoError(s.store.SaveCVEBypass(s.ctx, bypass))
|
||||
|
||||
var after CVEBypassModel
|
||||
s.Require().NoError(s.store.db.First(&after, bypass.ID).Error)
|
||||
s.Equal("after", after.Reason)
|
||||
s.False(after.CreatedAt.IsZero())
|
||||
s.WithinDuration(before.CreatedAt, after.CreatedAt, time.Second)
|
||||
}
|
||||
|
||||
// Test_V2_SaveCVEBypass_UpdateMissing tests that editing an unknown bypass fails.
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_SaveCVEBypass_UpdateMissing() {
|
||||
err := s.store.SaveCVEBypass(s.ctx, &metadata.CVEBypass{
|
||||
ID: "999999", Type: metadata.BypassTypeCVE, Target: "CVE-2024-0004", Reason: "x",
|
||||
CreatedBy: "[email protected]", ExpiresAt: time.Now().Add(time.Hour), Active: true,
|
||||
})
|
||||
s.Error(err)
|
||||
}
|
||||
|
||||
// Test_V2_GetActiveCVEBypasses tests retrieving active CVE bypasses
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_GetActiveCVEBypasses() {
|
||||
// Create active bypass with unique target
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresIdleEviction(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.db.Exec(
|
||||
"TRUNCATE packages, download_events, download_stats_hourly, download_stats_daily RESTART IDENTITY CASCADE").Error)
|
||||
}
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"list idle": checkListIdlePackages,
|
||||
"list expired": checkListExpiredPackages,
|
||||
"clear artifact expiry": checkClearArtifactExpiry,
|
||||
"delete keeps history": checkDeleteKeepsDownloadHistory,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
reset(t)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresHistoryTablesHaveNoPackageForeignKey(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
var referencing []string
|
||||
require.NoError(t, store.db.Raw(
|
||||
"SELECT conrelid::regclass::text FROM pg_constraint WHERE contype = 'f' AND confrelid = 'packages'::regclass",
|
||||
).Scan(&referencing).Error)
|
||||
for _, table := range []string{"download_events", "download_stats_hourly", "download_stats_daily"} {
|
||||
require.NotContains(t, referencing, table, "%s must not reference packages: a package delete would restrict or cascade over history", table)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func savePkg(t *testing.T, store *GORMStoreV2, name, version string, lastAccessed time.Time, expiresAt *time.Time) {
|
||||
t.Helper()
|
||||
savePkgIn(t, store, "npm", name, version, lastAccessed, expiresAt)
|
||||
}
|
||||
|
||||
func savePkgIn(t *testing.T, store *GORMStoreV2, registry, name, version string, lastAccessed time.Time, expiresAt *time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: registry, Name: name, Version: version,
|
||||
StorageKey: fmt.Sprintf("%s/%s/%s", registry, name, version),
|
||||
Size: 100, CachedAt: lastAccessed, LastAccessed: lastAccessed, ExpiresAt: expiresAt,
|
||||
}))
|
||||
}
|
||||
|
||||
func names(pkgs []*metadata.Package) []string {
|
||||
out := make([]string, len(pkgs))
|
||||
for i, p := range pkgs {
|
||||
out[i] = p.Name
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func checkListIdlePackages(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
savePkg(t, store, "idle-oldest", "1.0.0", now.Add(-10*24*time.Hour), nil)
|
||||
savePkg(t, store, "idle-middle", "1.0.0", now.Add(-9*24*time.Hour), nil)
|
||||
savePkg(t, store, "idle-newest", "1.0.0", now.Add(-8*24*time.Hour), nil)
|
||||
savePkg(t, store, "recent", "1.0.0", now.Add(-24*time.Hour), nil)
|
||||
savePkg(t, store, "touched", "1.0.0", now.Add(-12*24*time.Hour), nil)
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "touched", "1.0.0"))
|
||||
|
||||
cutoff := now.Add(-7 * 24 * time.Hour)
|
||||
|
||||
batch, err := store.ListIdlePackages(ctx, cutoff, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"idle-oldest", "idle-middle"}, names(batch), "oldest first, capped at the limit")
|
||||
require.Equal(t, "npm", batch[0].Registry)
|
||||
require.Equal(t, "npm/idle-oldest/1.0.0", batch[0].StorageKey)
|
||||
require.Equal(t, int64(100), batch[0].Size)
|
||||
|
||||
for _, p := range batch {
|
||||
require.NoError(t, store.DeletePackage(ctx, p.Registry, p.Name, p.Version))
|
||||
}
|
||||
batch, err = store.ListIdlePackages(ctx, cutoff, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"idle-newest"}, names(batch), "deleted rows leave the result; a touched row is not idle")
|
||||
|
||||
batch, err = store.ListIdlePackages(ctx, cutoff, 0)
|
||||
require.NoError(t, err, "a non-positive limit falls back to the default batch size")
|
||||
require.Equal(t, []string{"idle-newest"}, names(batch))
|
||||
}
|
||||
|
||||
func checkListExpiredPackages(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
past, future := now.Add(-time.Hour), now.Add(time.Hour)
|
||||
savePkg(t, store, "stale-meta", "list", now, &past)
|
||||
savePkg(t, store, "fresh-meta", "list", now, &future)
|
||||
savePkg(t, store, "no-expiry", "1.0.0", now, nil)
|
||||
|
||||
got, err := store.ListExpiredPackages(ctx, now, 10)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"stale-meta"}, names(got))
|
||||
}
|
||||
|
||||
func checkClearArtifactExpiry(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
exp := now.Add(24 * time.Hour)
|
||||
savePkg(t, store, "lodash", "4.17.21", now, &exp)
|
||||
savePkg(t, store, "left-pad", "1.3.0", now, &exp)
|
||||
savePkg(t, store, "lodash", "list", now, &exp)
|
||||
savePkg(t, store, "lodash", "page", now, &exp)
|
||||
savePkg(t, store, "lodash", "latest", now, &exp)
|
||||
savePkg(t, store, "lodash", "metadata", now, &exp)
|
||||
savePkgIn(t, store, "go", "golang.org/x/text/@v/v0.3.0.mod", "v0.3.0", now, &exp)
|
||||
savePkgIn(t, store, "go", "golang.org/x/text/@v/v0.3.0.info", "v0.3.0", now, &exp)
|
||||
// An npm package named like Go metadata is an artifact.
|
||||
savePkg(t, store, "left.info", "1.0.0", now, &exp)
|
||||
|
||||
cleared, err := store.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(3), cleared, "only the three artifacts lose their expiry")
|
||||
|
||||
for _, a := range [][2]string{{"lodash", "4.17.21"}, {"left-pad", "1.3.0"}, {"left.info", "1.0.0"}} {
|
||||
p, getErr := store.GetPackage(ctx, "npm", a[0], a[1])
|
||||
require.NoError(t, getErr)
|
||||
require.Nil(t, p.ExpiresAt, a[0])
|
||||
}
|
||||
for _, m := range [][2]string{
|
||||
{"lodash", "list"}, {"lodash", "page"}, {"lodash", "latest"}, {"lodash", "metadata"},
|
||||
} {
|
||||
p, getErr := store.GetPackage(ctx, "npm", m[0], m[1])
|
||||
require.NoError(t, getErr)
|
||||
require.NotNil(t, p.ExpiresAt, "metadata entry %s@%s keeps its freshness expiry", m[0], m[1])
|
||||
}
|
||||
for _, m := range [][2]string{
|
||||
{"golang.org/x/text/@v/v0.3.0.mod", "v0.3.0"}, {"golang.org/x/text/@v/v0.3.0.info", "v0.3.0"},
|
||||
} {
|
||||
p, getErr := store.GetPackage(ctx, "go", m[0], m[1])
|
||||
require.NoError(t, getErr)
|
||||
require.NotNil(t, p.ExpiresAt, "metadata entry %s@%s keeps its freshness expiry", m[0], m[1])
|
||||
}
|
||||
|
||||
again, err := store.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, again, "idempotent")
|
||||
}
|
||||
|
||||
// A deleted package must not change the download totals: history rows carry
|
||||
// package_id with no foreign key, and the soft delete keeps the package row.
|
||||
func checkDeleteKeepsDownloadHistory(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
recordDownloads(t, store, 3)
|
||||
// Two of the three downloads sit in a completed hour, ready to aggregate.
|
||||
require.NoError(t, store.db.Exec(
|
||||
"UPDATE download_events SET downloaded_at = ? WHERE id IN (SELECT id FROM (SELECT id FROM download_events ORDER BY id LIMIT 2) AS first_two)",
|
||||
time.Now().UTC().Add(-3*time.Hour)).Error)
|
||||
|
||||
total := func(label string) {
|
||||
t.Helper()
|
||||
for _, period := range []string{"1day", "7day", "30day"} {
|
||||
ts, err := store.GetTimeSeriesStats(ctx, period, "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(3), sumPoints(ts), "%s (%s)", label, period)
|
||||
}
|
||||
}
|
||||
total("before delete")
|
||||
|
||||
require.NoError(t, store.DeletePackage(ctx, "npm", "left-pad", "1.3.0"))
|
||||
total("after delete")
|
||||
|
||||
// Re-caching the key hard-deletes the stale soft-deleted row.
|
||||
now := time.Now()
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
Size: 10, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
total("after re-cache")
|
||||
|
||||
// Aggregation writes package_id rows for a package that is gone again.
|
||||
require.NoError(t, store.DeletePackage(ctx, "npm", "left-pad", "1.3.0"))
|
||||
require.NoError(t, store.AggregateDownloadData(ctx))
|
||||
total("after delete and aggregation")
|
||||
}
|
||||
|
||||
func TestListIdlePackages(t *testing.T) { checkListIdlePackages(t, newTimeSeriesStore(t)) }
|
||||
func TestListExpiredPackages(t *testing.T) { checkListExpiredPackages(t, newTimeSeriesStore(t)) }
|
||||
func TestClearArtifactExpiry(t *testing.T) { checkClearArtifactExpiry(t, newTimeSeriesStore(t)) }
|
||||
func TestDeletePackageKeepsDownloadHistory(t *testing.T) {
|
||||
checkDeleteKeepsDownloadHistory(t, newTimeSeriesStore(t))
|
||||
}
|
||||
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListIdlePackages() { checkListIdlePackages(s.T(), s.store) }
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListExpiredPackages() {
|
||||
checkListExpiredPackages(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ClearArtifactExpiry() {
|
||||
checkClearArtifactExpiry(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_DeleteKeepsDownloadHistory() {
|
||||
checkDeleteKeepsDownloadHistory(s.T(), s.store)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The missed-day repair on the production dialect: hourly rows are written directly so the
|
||||
// test needs no download_events partition for a past month.
|
||||
func TestPostgresDailyRollupCoversMissedDay(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, _ := newPostgresStore(t)
|
||||
day := time.Now().UTC().Truncate(24 * time.Hour).Add(-10 * 24 * time.Hour)
|
||||
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
Size: 10, CachedAt: day, LastAccessed: day,
|
||||
}))
|
||||
registryID, err := store.getRegistryID("npm")
|
||||
require.NoError(t, err)
|
||||
var packageID int64
|
||||
require.NoError(t, store.db.Table("packages").Select("id").Where("name = ?", "left-pad").Scan(&packageID).Error)
|
||||
for _, hour := range []int{5, 6, 7} {
|
||||
require.NoError(t, store.db.Exec(
|
||||
`INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
VALUES (?, ?, ?, 1, 1, 0, NOW(), NOW())`, registryID, packageID, day.Add(time.Duration(hour)*time.Hour)).Error)
|
||||
}
|
||||
|
||||
for d := 2; d <= 9; d++ {
|
||||
at := day.Add(time.Duration(d)*24*time.Hour + 30*time.Minute)
|
||||
store.aggregationWorker.now = func() time.Time { return at }
|
||||
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||
}
|
||||
|
||||
store.now = func() time.Time { return day.Add(9*24*time.Hour + time.Hour) }
|
||||
ts, err := store.GetTimeSeriesStats(ctx, "30day", "")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, sumPoints(ts))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newRollupStore adds the unique indexes Postgres gets from the partition manager,
|
||||
// so INSERT OR REPLACE upserts as the ON CONFLICT clauses do there.
|
||||
func newRollupStore(t *testing.T) *GORMStoreV2 {
|
||||
t.Helper()
|
||||
store := newTimeSeriesStore(t)
|
||||
for _, stmt := range statsUpsertIndexes {
|
||||
require.NoError(t, store.db.Exec(stmt).Error)
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
// tick mirrors AggregationWorker.Start: an hourly pass, plus the daily pass in hour 0.
|
||||
func tick(t *testing.T, store *GORMStoreV2, at time.Time, daily bool) {
|
||||
t.Helper()
|
||||
store.aggregationWorker.now = func() time.Time { return at }
|
||||
require.NoError(t, store.aggregationWorker.AggregateHourly())
|
||||
if daily && at.Hour() == 0 {
|
||||
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||
}
|
||||
}
|
||||
|
||||
func seedEventsAt(t *testing.T, store *GORMStoreV2, times ...time.Time) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
Size: 10, CachedAt: times[0], LastAccessed: times[0],
|
||||
}))
|
||||
for _, at := range times {
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "left-pad", "1.3.0"))
|
||||
var id int64
|
||||
require.NoError(t, store.db.Table("download_events").Select("MAX(id)").Scan(&id).Error)
|
||||
require.NoError(t, store.db.Exec("UPDATE download_events SET downloaded_at = ? WHERE id = ?", at, id).Error)
|
||||
}
|
||||
}
|
||||
|
||||
func totalAt(t *testing.T, store *GORMStoreV2, at time.Time, period string) int64 {
|
||||
t.Helper()
|
||||
store.now = func() time.Time { return at }
|
||||
ts, err := store.GetTimeSeriesStats(context.Background(), period, "")
|
||||
require.NoError(t, err)
|
||||
return sumPoints(ts)
|
||||
}
|
||||
|
||||
// A download in the last hour of a day that the daily pass ran before that hour was aggregated.
|
||||
func TestDailyRollupKeepsLastHourOfDay(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(23*time.Hour+30*time.Minute))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+2*time.Minute), true) // cutoff 23:00: the 23:30 event is not counted yet
|
||||
tick(t, store, day.Add(25*time.Hour+2*time.Minute), true)
|
||||
tick(t, store, day.Add(48*time.Hour+3*time.Minute), true)
|
||||
|
||||
require.EqualValues(t, 2, totalAt(t, store, day.Add(48*time.Hour+10*time.Minute), "7day"))
|
||||
}
|
||||
|
||||
// A day whose midnight daily pass never ran must still be rolled up before its hourly rows expire.
|
||||
func TestDailyRollupCoversMissedDay(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(5*time.Hour), day.Add(6*time.Hour), day.Add(7*time.Hour))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+30*time.Minute), false) // process restarting at midnight: no daily pass
|
||||
for d := 2; d <= 9; d++ {
|
||||
tick(t, store, day.Add(time.Duration(d)*24*time.Hour+30*time.Minute), true)
|
||||
}
|
||||
|
||||
require.EqualValues(t, 3, totalAt(t, store, day.Add(9*24*time.Hour+time.Hour), "30day"))
|
||||
}
|
||||
|
||||
// Hourly rows and events never overcount a day, so a rollup that is behind them must not win.
|
||||
func TestTimeSeriesKeepsLateDownloadsAheadOfRollup(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(23*time.Hour+30*time.Minute))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+2*time.Minute), true) // rollup counts one download
|
||||
tick(t, store, day.Add(25*time.Hour+2*time.Minute), true) // the 23:30 download reaches the hourly table
|
||||
|
||||
require.EqualValues(t, 2, totalAt(t, store, day.Add(26*time.Hour), "7day"))
|
||||
}
|
||||
|
||||
// A rollup larger than the hourly rows still wins once the hourly rows have been trimmed.
|
||||
func TestTimeSeriesKeepsRollupWhenHourlyRowsAreGone(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(11*time.Hour), day.Add(12*time.Hour))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+30*time.Minute), true)
|
||||
require.NoError(t, store.db.Exec("DELETE FROM download_stats_hourly WHERE time_bucket = ?", day.Add(12*time.Hour)).Error)
|
||||
|
||||
require.EqualValues(t, 3, totalAt(t, store, day.Add(26*time.Hour), "7day"))
|
||||
}
|
||||
@@ -14,6 +14,38 @@ import (
|
||||
// Callers should treat it as a non-fatal capability check.
|
||||
var ErrNotImplemented = errors.New("metadata: operation not implemented by this backend")
|
||||
|
||||
// DefaultBatchSize bounds the rows a list query returns when the caller passes no limit.
|
||||
const DefaultBatchSize = 500
|
||||
|
||||
// MetadataVersions are the cache-key versions of metadata pages (index, list, latest).
|
||||
var MetadataVersions = []string{"list", "page", "latest", "metadata"}
|
||||
|
||||
// MetadataNameSuffixes mark Go module metadata files (.mod, .info).
|
||||
var MetadataNameSuffixes = []string{".mod", ".info"}
|
||||
|
||||
// GoRegistry is the registry whose cache keys carry the name suffixes above.
|
||||
const GoRegistry = "go"
|
||||
|
||||
// IsMetadataEntry reports whether a cache entry is a metadata page that must
|
||||
// refresh, as opposed to an immutable artifact. The name suffixes apply to Go
|
||||
// only: an npm or PyPI package may legitimately end in .mod or .info.
|
||||
func IsMetadataEntry(registry, name, version string) bool {
|
||||
for _, v := range MetadataVersions {
|
||||
if version == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if registry != GoRegistry {
|
||||
return false
|
||||
}
|
||||
for _, suffix := range MetadataNameSuffixes {
|
||||
if strings.HasSuffix(name, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Store is an alias for MetadataStore for convenience
|
||||
type Store = MetadataStore
|
||||
|
||||
@@ -31,9 +63,21 @@ type MetadataStore interface {
|
||||
// ListPackages lists packages with optional filtering
|
||||
ListPackages(ctx context.Context, opts *ListOptions) ([]*Package, error)
|
||||
|
||||
// UpdateDownloadCount increments download counter
|
||||
// UpdateDownloadCount increments download counter and stamps last_accessed
|
||||
UpdateDownloadCount(ctx context.Context, registry, name, version string) error
|
||||
|
||||
// ListIdlePackages returns up to limit packages last accessed before
|
||||
// idleBefore, oldest first. A limit <= 0 means DefaultBatchSize.
|
||||
ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*Package, error)
|
||||
|
||||
// ListExpiredPackages returns up to limit packages whose ExpiresAt is before
|
||||
// the given time, oldest first. A limit <= 0 means DefaultBatchSize.
|
||||
ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*Package, error)
|
||||
|
||||
// ClearArtifactExpiry removes ExpiresAt from every non-metadata entry and
|
||||
// returns the number of rows changed. It is idempotent.
|
||||
ClearArtifactExpiry(ctx context.Context) (int64, error)
|
||||
|
||||
// GetStats returns statistics
|
||||
GetStats(ctx context.Context, registry string) (*Stats, error)
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package metadata
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsMetadataEntry(t *testing.T) {
|
||||
tests := []struct {
|
||||
registry, name, version string
|
||||
want bool
|
||||
}{
|
||||
{"npm", "lodash", "metadata", true},
|
||||
{"pypi", "foo", "page", true},
|
||||
{"go", "example.com/m/@v/list", "list", true},
|
||||
{"go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", true},
|
||||
{"go", "example.com/m/@v/v1.0.0.info", "v1.0.0", true},
|
||||
{"go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", false},
|
||||
{"npm", "left.info", "1.0.0", false},
|
||||
{"pypi", "foo.mod", "foo.mod-1.0.tar.gz", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := IsMetadataEntry(tt.registry, tt.name, tt.version); got != tt.want {
|
||||
t.Errorf("IsMetadataEntry(%q, %q, %q) = %v, want %v", tt.registry, tt.name, tt.version, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,14 @@ var (
|
||||
[]string{"reason"}, // ttl, lru, manual
|
||||
)
|
||||
|
||||
// WebSocketEventsDropped counts realtime events dropped because the broadcast channel was full.
|
||||
WebSocketEventsDropped = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "gohoarder_websocket_events_dropped_total",
|
||||
Help: "Realtime dashboard events dropped because the broadcast channel was full",
|
||||
},
|
||||
)
|
||||
|
||||
// Storage metrics
|
||||
StorageOperations = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package pypi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The cache key is pypi/<name>/<filename>, so original_url must name that same file.
|
||||
func TestHandlePackageFile_OriginalURLFilenameBound(t *testing.T) {
|
||||
const path = "/example/example-1.0.0-py3-none-any.whl"
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
originalURL string
|
||||
wantReject bool
|
||||
}{
|
||||
{"other file on allowed host", path, "https://files.pythonhosted.org/packages/ab/cd/ef/evil-9.9.9-py3-none-any.whl", true},
|
||||
{"other project same version", path, "https://files.pythonhosted.org/packages/ab/cd/ef/other-1.0.0-py3-none-any.whl", true},
|
||||
{"sidecar of another file", path + ".metadata", "https://files.pythonhosted.org/packages/ab/cd/ef/evil-9.9.9-py3-none-any.whl", true},
|
||||
{"same file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
|
||||
{"same file with query", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl?x=1", false},
|
||||
{"sidecar of same file", path + ".metadata", "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
|
||||
}
|
||||
|
||||
h := newHandlerForSSRFTest()
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
q := url.Values{}
|
||||
q.Set("original_url", tt.originalURL)
|
||||
req := httptest.NewRequest(http.MethodGet, tt.path+"?"+q.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// A nil cache panics once the guards pass; that means "not rejected".
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
h.handlePackageFile(req.Context(), w, req, tt.path)
|
||||
}()
|
||||
|
||||
rejected := w.Code == http.StatusBadRequest
|
||||
if rejected != tt.wantReject {
|
||||
t.Errorf("rejected=%v want %v (code=%d body=%q)", rejected, tt.wantReject, w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
gopath "path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -285,6 +286,17 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
|
||||
http.Error(w, "original_url host not allowed", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// The cache key is built from the request path, so the fetched file must
|
||||
// be the one the path names; otherwise any file on an allowed host could
|
||||
// be stored under another package's key.
|
||||
if gopath.Base(parsed.Path) != filename {
|
||||
log.Warn().
|
||||
Str("original_url", originalURL).
|
||||
Str("filename", filename).
|
||||
Msg("Rejected original_url naming a different file")
|
||||
http.Error(w, "original_url does not match requested file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// A PEP 658 sidecar is a view of its wheel, not a package: stream it
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A vulnerability covered by an active bypass must not block under any block_on_severity.
|
||||
func TestCheckVulnerabilities_BypassedCVENeverBlocks(t *testing.T) {
|
||||
policies := []string{"CRITICAL", "HIGH", "MODERATE", "MEDIUM", "LOW", "none", ""}
|
||||
severities := []string{"CRITICAL", "HIGH", "MODERATE", "MEDIUM", "LOW", "UNKNOWN"}
|
||||
|
||||
for _, policy := range policies {
|
||||
for _, severity := range severities {
|
||||
t.Run(policy+"/"+severity, func(t *testing.T) {
|
||||
store := &stubBypassStore{
|
||||
stubMetadataStore: &stubMetadataStore{},
|
||||
bypasses: []*metadata.CVEBypass{
|
||||
{ID: "b1", Type: metadata.BypassTypeCVE, Target: "CVE-1", Active: true, ExpiresAt: time.Now().Add(time.Hour)},
|
||||
},
|
||||
scan: &metadata.ScanResult{
|
||||
ID: "r", Scanner: "stub", ScannedAt: time.Now(), Status: metadata.ScanStatusVulnerable,
|
||||
Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: severity}},
|
||||
},
|
||||
}
|
||||
mgr, err := New(config.SecurityConfig{
|
||||
Enabled: true,
|
||||
BlockOnSeverity: policy,
|
||||
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1},
|
||||
}, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
require.False(t, blocked, "bypassed CVE blocked: %s", reason)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An unbypassed vulnerability at or above the policy severity still blocks.
|
||||
func TestCheckVulnerabilities_UnbypassedCVEBlocksAtPolicy(t *testing.T) {
|
||||
store := &stubBypassStore{
|
||||
stubMetadataStore: &stubMetadataStore{},
|
||||
bypasses: []*metadata.CVEBypass{
|
||||
{ID: "b1", Type: metadata.BypassTypeCVE, Target: "CVE-1", Active: true, ExpiresAt: time.Now().Add(time.Hour)},
|
||||
},
|
||||
scan: &metadata.ScanResult{
|
||||
ID: "r", Scanner: "stub", ScannedAt: time.Now(), Status: metadata.ScanStatusVulnerable,
|
||||
Vulnerabilities: []metadata.Vulnerability{
|
||||
{ID: "CVE-1", Severity: "LOW"},
|
||||
{ID: "CVE-2", Severity: "LOW"},
|
||||
},
|
||||
},
|
||||
}
|
||||
mgr, err := New(config.SecurityConfig{
|
||||
Enabled: true,
|
||||
BlockOnSeverity: "LOW",
|
||||
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1},
|
||||
}, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
require.True(t, blocked)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// versionRecorder remembers the version each scan asked about.
|
||||
type versionRecorder struct {
|
||||
versions []string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *versionRecorder) Name() string { return "recorder" }
|
||||
|
||||
func (s *versionRecorder) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
s.mu.Lock()
|
||||
s.versions = append(s.versions, version)
|
||||
s.mu.Unlock()
|
||||
return &metadata.ScanResult{
|
||||
ID: "r", Registry: registry, PackageName: name, PackageVersion: version,
|
||||
Scanner: "recorder", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *versionRecorder) Health(context.Context) error { return nil }
|
||||
|
||||
type packageStore struct {
|
||||
*stubMetadataStore
|
||||
pkg *metadata.Package
|
||||
}
|
||||
|
||||
func (s *packageStore) GetPackage(context.Context, string, string, string) (*metadata.Package, error) {
|
||||
return s.pkg, nil
|
||||
}
|
||||
|
||||
// PyPI artifacts are cached under their file name; scanners must be asked about the release version.
|
||||
func TestScanAsksScannersForReleaseVersion(t *testing.T) {
|
||||
const wheel = "requests-2.19.0-py3-none-any.whl"
|
||||
tests := []struct {
|
||||
name string
|
||||
pkg *metadata.Package
|
||||
want string
|
||||
}{
|
||||
{"pypi file", &metadata.Package{Version: wheel, ReleaseVersion: "2.19.0"}, "2.19.0"},
|
||||
{"npm tarball has no release version", &metadata.Package{Version: wheel}, wheel},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
store := &packageStore{stubMetadataStore: &stubMetadataStore{}, pkg: tt.pkg}
|
||||
mgr := newTestManager(t, store)
|
||||
rec := &versionRecorder{}
|
||||
mgr.RegisterScanner(rec)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "pypi", "requests", wheel, "/tmp/x"))
|
||||
require.Equal(t, []string{tt.want}, rec.versions)
|
||||
require.Len(t, store.savedResults, 1)
|
||||
require.Equal(t, wheel, store.savedResults[0].PackageVersion, "the result stays keyed by the cache version")
|
||||
})
|
||||
}
|
||||
}
|
||||
+30
-4
@@ -262,6 +262,8 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
Str("version", version).
|
||||
Msg("Starting security scan")
|
||||
|
||||
scanVersion := m.scanVersion(ctx, registry, packageName, version)
|
||||
|
||||
// Collect results from all scanners
|
||||
var scanResults []*metadata.ScanResult
|
||||
scannerNames := make([]string, 0)
|
||||
@@ -277,7 +279,7 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
continue
|
||||
}
|
||||
|
||||
result, err := scanner.Scan(ctx, registry, packageName, version, filePath)
|
||||
result, err := scanner.Scan(ctx, registry, packageName, scanVersion, filePath)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
@@ -355,6 +357,8 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
|
||||
// Merge and deduplicate results from all scanners
|
||||
mergedResult := m.mergeResults(scanResults, scannerNames)
|
||||
// The store finds the package by its cache version, not the release version.
|
||||
mergedResult.PackageVersion = version
|
||||
|
||||
// Save consolidated result to metadata store
|
||||
if err := m.metadataStore.SaveScanResult(ctx, mergedResult); err != nil {
|
||||
@@ -384,6 +388,16 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
return nil
|
||||
}
|
||||
|
||||
// scanVersion is the version scanners are asked about. PyPI artifacts are cached
|
||||
// under their file name; the release version is on the package row.
|
||||
func (m *Manager) scanVersion(ctx context.Context, registry, packageName, version string) string {
|
||||
pkg, err := m.metadataStore.GetPackage(ctx, registry, packageName, version)
|
||||
if err != nil || pkg == nil || pkg.ReleaseVersion == "" {
|
||||
return version
|
||||
}
|
||||
return pkg.ReleaseVersion
|
||||
}
|
||||
|
||||
// mergeResults merges and deduplicates scan results from multiple scanners
|
||||
func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []string) *metadata.ScanResult {
|
||||
if len(results) == 0 {
|
||||
@@ -528,6 +542,15 @@ func normalizeBypassPackageName(registry, name string) string {
|
||||
return name
|
||||
}
|
||||
|
||||
// releaseVersionKey returns "registry/name@release_version" for packages keyed by file name (PyPI), else "".
|
||||
func (m *Manager) releaseVersionKey(ctx context.Context, registry, packageName, version, bypassName string) string {
|
||||
pkg, err := m.metadataStore.GetPackage(ctx, registry, packageName, version)
|
||||
if err != nil || pkg == nil || pkg.ReleaseVersion == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s/%s@%s", registry, bypassName, pkg.ReleaseVersion)
|
||||
}
|
||||
|
||||
// CheckVulnerabilities checks if a package exceeds vulnerability thresholds
|
||||
func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageName, version string) (bool, string, error) {
|
||||
if !m.enabled {
|
||||
@@ -545,10 +568,11 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
bypassName := normalizeBypassPackageName(registry, packageName)
|
||||
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
|
||||
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
|
||||
releaseKey := m.releaseVersionKey(ctx, registry, packageName, version, bypassName)
|
||||
|
||||
for _, bypass := range bypasses {
|
||||
if bypass.Type == metadata.BypassTypePackage && bypass.Active {
|
||||
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion {
|
||||
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion || (releaseKey != "" && bypass.Target == releaseKey) {
|
||||
log.Info().
|
||||
Str("package", packageKey).
|
||||
Str("bypass_id", bypass.ID).
|
||||
@@ -605,7 +629,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
for _, bypass := range bypasses {
|
||||
if bypass.Type == metadata.BypassTypeCVE && bypass.Active {
|
||||
// Check if bypass applies to this package (if AppliesTo is set)
|
||||
if bypass.AppliesTo != "" && bypass.AppliesTo != packageKey && bypass.AppliesTo != packageKeyNoVersion {
|
||||
if bypass.AppliesTo != "" && bypass.AppliesTo != packageKey && bypass.AppliesTo != packageKeyNoVersion && (releaseKey == "" || bypass.AppliesTo != releaseKey) {
|
||||
continue // This bypass doesn't apply to this package
|
||||
}
|
||||
bypassedCVEs[strings.ToUpper(bypass.Target)] = bypass
|
||||
@@ -614,6 +638,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
|
||||
// Count vulnerabilities by severity, excluding bypassed CVEs
|
||||
severityCounts := make(map[string]int)
|
||||
remaining := 0
|
||||
for _, vuln := range result.Vulnerabilities {
|
||||
// Check if this CVE is bypassed
|
||||
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
|
||||
@@ -627,6 +652,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
continue
|
||||
}
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
remaining++
|
||||
}
|
||||
|
||||
// Check against thresholds
|
||||
@@ -677,7 +703,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
return true, "Package has MODERATE, HIGH, or CRITICAL vulnerabilities", nil
|
||||
}
|
||||
case "LOW":
|
||||
if len(result.Vulnerabilities) > 0 {
|
||||
if remaining > 0 {
|
||||
return true, "Package has vulnerabilities", nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,13 @@ func (m *stubMetadataStore) GetTimeSeriesStats(context.Context, string, string)
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) AggregateDownloadData(context.Context) error { return nil }
|
||||
func (m *stubMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
func (m *stubMetadataStore) SaveAPIKey(context.Context, *metadata.APIKey) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
@@ -453,3 +460,41 @@ func TestScanner_DisabledReportsNotEnabled(t *testing.T) {
|
||||
assert.False(t, mgr.Enabled())
|
||||
assert.True(t, newTestManager(t, &stubMetadataStore{}).Enabled())
|
||||
}
|
||||
|
||||
// releasePackageStore returns a PyPI-style package whose cache key is a file name.
|
||||
type releasePackageStore struct {
|
||||
*stubBypassStore
|
||||
}
|
||||
|
||||
func (m *releasePackageStore) GetPackage(_ context.Context, _, _, version string) (*metadata.Package, error) {
|
||||
return &metadata.Package{Name: "six", Version: version, ReleaseVersion: "1.17.0"}, nil
|
||||
}
|
||||
|
||||
func TestCheckVulnerabilities_PackageBypassMatchesReleaseVersion(t *testing.T) {
|
||||
const file = "six-1.17.0-py2.py3-none-any.whl"
|
||||
cases := []struct {
|
||||
name string
|
||||
target string
|
||||
blocked bool
|
||||
}{
|
||||
{"release version target", "pypi/[email protected]", false},
|
||||
{"file name target", "pypi/six@" + file, false},
|
||||
{"other release", "pypi/[email protected]", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
store := &releasePackageStore{&stubBypassStore{
|
||||
stubMetadataStore: &stubMetadataStore{},
|
||||
bypasses: []*metadata.CVEBypass{{ID: "b1", Type: metadata.BypassTypePackage, Target: tc.target, Active: true}},
|
||||
scan: &metadata.ScanResult{
|
||||
ID: "r", Scanner: "stub", ScannedAt: time.Now(), Status: metadata.ScanStatusVulnerable,
|
||||
Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: "HIGH"}},
|
||||
},
|
||||
}}
|
||||
mgr := newTestManager(t, store)
|
||||
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "pypi", "six", file)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.blocked, blocked)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,12 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
|
||||
// only successfully renamed files. Quota check happens before increment
|
||||
// to avoid transient inflation seen by concurrent Puts.
|
||||
fs.mu.Lock()
|
||||
if fs.quota > 0 && fs.used+written > fs.quota {
|
||||
// An overwrite releases the bytes of the file it replaces.
|
||||
var replaced int64
|
||||
if info, statErr := root.Stat(relPath); statErr == nil {
|
||||
replaced = info.Size()
|
||||
}
|
||||
if fs.quota > 0 && fs.used-replaced+written > fs.quota {
|
||||
fs.mu.Unlock()
|
||||
_ = root.Remove(tempPath)
|
||||
metrics.RecordStorageOperation("filesystem", "put", "quota_exceeded")
|
||||
@@ -174,7 +179,7 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
|
||||
metrics.RecordStorageOperation("filesystem", "put", "error")
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to rename temp file")
|
||||
}
|
||||
fs.used += written
|
||||
fs.used += written - replaced
|
||||
currentUsed := fs.used
|
||||
fs.mu.Unlock()
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Used bytes must equal the bytes on disk after a key is overwritten.
|
||||
func TestPutOverwriteKeepsUsageExact(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fs, err := New(t.TempDir(), 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("x", 400)), nil))
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("y", 300)), nil))
|
||||
|
||||
quota, err := fs.GetQuota(ctx)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 300, quota.Used)
|
||||
|
||||
require.NoError(t, fs.Delete(ctx, "npm/a/metadata"))
|
||||
quota, err = fs.GetQuota(ctx)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, quota.Used)
|
||||
}
|
||||
|
||||
// An overwrite that fits once the old bytes are released must not hit the quota.
|
||||
func TestPutOverwriteWithinQuota(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fs, err := New(t.TempDir(), 500)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("x", 400)), nil))
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("y", 450)), nil))
|
||||
}
|
||||
+26
-1
@@ -7,10 +7,13 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
|
||||
)
|
||||
|
||||
// EventType represents the type of event being broadcast
|
||||
@@ -59,6 +62,8 @@ type Server struct {
|
||||
unregister chan *Client
|
||||
upgrader websocket.Upgrader
|
||||
mu sync.RWMutex
|
||||
dropped atomic.Uint64
|
||||
lastWarn atomic.Int64
|
||||
}
|
||||
|
||||
// Config holds WebSocket server configuration
|
||||
@@ -222,10 +227,30 @@ func (s *Server) Broadcast(eventType EventType, data map[string]interface{}) {
|
||||
select {
|
||||
case s.broadcast <- event:
|
||||
default:
|
||||
log.Warn().Msg("Broadcast channel full - dropping event")
|
||||
s.recordDrop()
|
||||
}
|
||||
}
|
||||
|
||||
// dropWarnInterval bounds the drop warning to one line per interval, so a burst does not flood the log.
|
||||
const dropWarnInterval = time.Minute
|
||||
|
||||
// recordDrop counts a dropped event and warns at most once per dropWarnInterval.
|
||||
func (s *Server) recordDrop() {
|
||||
total := s.dropped.Add(1)
|
||||
metrics.WebSocketEventsDropped.Inc()
|
||||
now := time.Now().UnixNano()
|
||||
last := s.lastWarn.Load()
|
||||
if now-last < int64(dropWarnInterval) || !s.lastWarn.CompareAndSwap(last, now) {
|
||||
return
|
||||
}
|
||||
log.Warn().Uint64("dropped_total", total).Msg("Broadcast channel full - dropping events")
|
||||
}
|
||||
|
||||
// Dropped returns how many events were dropped because the broadcast channel was full.
|
||||
func (s *Server) Dropped() uint64 {
|
||||
return s.dropped.Load()
|
||||
}
|
||||
|
||||
// BroadcastEvent satisfies the events.Broadcaster contract used by
|
||||
// cache/scanner sub-systems. It accepts a string event type and an
|
||||
// arbitrary payload (typically map[string]any) and forwards to the
|
||||
|
||||
Reference in New Issue
Block a user