mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-28 06:46:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a457e3d2e8 | ||
|
|
ba8bc392ec | ||
|
|
1512230ab3 | ||
|
|
bd9d686383 | ||
|
|
4d31e535ff | ||
|
|
fe2d9f8b3a | ||
|
|
a84f080b79 | ||
|
|
9b4659218c | ||
|
|
1256756057 | ||
|
|
262771d224 | ||
|
|
536f35ab55 | ||
|
|
5a9d104b37 | ||
|
|
f2049383cb | ||
|
|
549d56e0a1 | ||
|
|
31db940014 | ||
|
|
f46e079cee | ||
|
|
ae5167ffa9 | ||
|
|
787c757827 | ||
|
|
ac4f39322c | ||
|
|
db5ca2539f | ||
|
|
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
|
||||
|
||||
@@ -85,6 +85,8 @@ server {
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
proxy_set_header Connection "";
|
||||
# The backend authenticates by API-key header; browser session cookies only bloat the request.
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# Timeouts for long-running operations
|
||||
proxy_connect_timeout 60s;
|
||||
@@ -122,6 +124,7 @@ server {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# WebSocket timeouts
|
||||
proxy_connect_timeout 7d;
|
||||
|
||||
@@ -193,6 +193,7 @@ server:
|
||||
host: "0.0.0.0"
|
||||
read_timeout: "5m"
|
||||
write_timeout: "5m"
|
||||
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
|
||||
storage:
|
||||
backend: "filesystem" # Options: filesystem, s3, smb
|
||||
@@ -233,7 +234,12 @@ 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
|
||||
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
|
||||
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
|
||||
pypi: 12h
|
||||
cleanup_interval: 1h
|
||||
|
||||
logging:
|
||||
level: "info" # debug, info, warn, error
|
||||
@@ -245,6 +251,17 @@ 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` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
|
||||
|
||||
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
|
||||
|
||||
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:
|
||||
@@ -876,10 +893,29 @@ Access the web dashboard at **http://localhost:8080**
|
||||
**List Packages:**
|
||||
```bash
|
||||
GET /api/packages
|
||||
GET /api/packages?registry=npm
|
||||
GET /api/packages?status=vulnerable
|
||||
GET /api/packages?page=1&page_size=25
|
||||
GET /api/packages?registry=npm&q=axios&page_size=25
|
||||
GET /api/packages?sort=cached_at&order=desc&page_size=10
|
||||
```
|
||||
|
||||
The dashboard groups versions under a package, so paging counts packages (a
|
||||
registry and name pair), not rows. Without `page` and `page_size` the call
|
||||
returns every package in one response, with no row cap.
|
||||
|
||||
| Parameter | Meaning |
|
||||
|---|---|
|
||||
| `page` | 1-based page of groups. Default 1. |
|
||||
| `page_size` | Groups per page. Default 25 when `page` is set, at most 200. |
|
||||
| `registry` | Only this registry, for example `npm`, `pypi` or `go`. |
|
||||
| `q` | Case-insensitive search in name, version and release version. |
|
||||
| `sort` | `name` (default, ascending), `cached_at`, `downloads` or `size` (both descending). |
|
||||
| `order` | `asc` or `desc`, to override the default direction of `sort`. |
|
||||
|
||||
`packages` holds every version row of each group on the page, in group order
|
||||
and newest first within a group. `total` is the number of rows returned.
|
||||
`total_groups` is the number of groups that match the filters across all pages.
|
||||
A paged response also echoes `page` and `page_size`.
|
||||
|
||||
**Package Details:**
|
||||
```bash
|
||||
GET /api/packages/:registry/:name/:version
|
||||
@@ -909,7 +945,10 @@ GET /api/packages/:registry/:name/:version
|
||||
}
|
||||
}
|
||||
],
|
||||
"total": 42
|
||||
"total": 1,
|
||||
"total_groups": 42,
|
||||
"page": 1,
|
||||
"page_size": 25
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+12
-5
@@ -10,8 +10,13 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080 # Backend API server port
|
||||
read_timeout: "5m"
|
||||
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
write_timeout: "5m"
|
||||
idle_timeout: "2m"
|
||||
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
|
||||
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
|
||||
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
|
||||
allowed_origins: []
|
||||
tls:
|
||||
enabled: false
|
||||
cert_file: ""
|
||||
@@ -89,14 +94,16 @@ metadata:
|
||||
log_level: "warn" # GORM log level: silent, error, warn, info
|
||||
|
||||
cache:
|
||||
default_ttl: "168h" # 7 days
|
||||
default_ttl: "24h" # 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
|
||||
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
|
||||
max_size_bytes: 536870912000 # 500GB
|
||||
per_project_quota: 53687091200 # 50GB
|
||||
ttl_overrides:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
security:
|
||||
enabled: false
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
describe('Dashboard.vue', () => {
|
||||
beforeEach(() => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
|
||||
|
||||
beforeEach(async () => {
|
||||
router = await createTestRouter('/')
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
// Mock the fetch functions to prevent actual API calls
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders dashboard component', () => {
|
||||
@@ -127,7 +132,7 @@ describe('Dashboard.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -144,22 +149,12 @@ describe('Dashboard.vue', () => {
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
})
|
||||
|
||||
it('shows recent packages sorted by cached_at', async () => {
|
||||
it('lists recent packages in the order the store holds them, newest first', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'old-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
@@ -170,46 +165,33 @@ describe('Dashboard.vue', () => {
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'old-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
|
||||
|
||||
// new-package should appear before old-package since it's more recent
|
||||
// The store sorts by cached_at; the view keeps that order
|
||||
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
|
||||
recentPackagesSection.indexOf('old-package')
|
||||
)
|
||||
})
|
||||
|
||||
it('limits recent packages to 10 items', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = Array.from({ length: 15 }, (_, i) => ({
|
||||
id: `${i}`,
|
||||
registry: 'npm',
|
||||
name: `package${i}`,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
|
||||
last_accessed: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
|
||||
download_count: i,
|
||||
}))
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const recentSection = wrapper.text().split('Recent packages')[1]
|
||||
// Count how many "package" strings appear (each package has the word "package" in its name)
|
||||
const packageCount = (recentSection.match(/package\d+/g) || []).length
|
||||
expect(packageCount).toBeLessThanOrEqual(10)
|
||||
})
|
||||
|
||||
it('handles empty packages array', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = []
|
||||
store.recentPackages = []
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('0')
|
||||
|
||||
@@ -39,35 +39,38 @@
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TrendChart compact class="min-w-0" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -75,7 +78,7 @@
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="packages.length === 0"
|
||||
v-if="recentPackages.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
@@ -124,10 +127,11 @@ import {
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
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,
|
||||
@@ -140,7 +144,7 @@ import {
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { packages, stats, loading, error } = storeToRefs(store)
|
||||
const { recentPackages, stats, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
@@ -190,7 +194,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 +255,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) },
|
||||
@@ -258,7 +263,7 @@ const packageColumns: DataTableColumn<Package>[] = [
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void store.fetchPackages()
|
||||
void store.fetchRecentPackages()
|
||||
}
|
||||
|
||||
function getChartLabel(index: number): string {
|
||||
@@ -290,14 +295,6 @@ function getChartLabel(index: number): string {
|
||||
return labels[selectedPeriod.value]?.(index) || `${index}`
|
||||
}
|
||||
|
||||
// API returns clean, deduplicated data - just sort and limit
|
||||
const recentPackages = computed(() => {
|
||||
return packages.value
|
||||
.slice()
|
||||
.sort((a, b) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
|
||||
.slice(0, 10)
|
||||
})
|
||||
|
||||
// Watch for period changes and fetch new data
|
||||
watch(selectedPeriod, () => {
|
||||
fetchTimeSeriesData()
|
||||
@@ -308,9 +305,7 @@ onMounted(async () => {
|
||||
// initial polling resolves. Singleton survives navigation, so we
|
||||
// intentionally do not disconnect on unmount.
|
||||
rt.connect()
|
||||
await store.fetchStats()
|
||||
await store.fetchPackages()
|
||||
await fetchTimeSeriesData()
|
||||
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), fetchTimeSeriesData()])
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
|
||||
@@ -6,6 +6,14 @@ import { defineComponent, h } from 'vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
|
||||
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
|
||||
|
||||
// A page as the server sends it: whole groups, flattened to rows.
|
||||
function setRows(store: ReturnType<typeof usePackageStore>, packages: Row[]) {
|
||||
const groups = new Set(packages.map((p) => `${p.registry}:${p.name}`))
|
||||
store.packagePage = { packages, totalGroups: groups.size, page: 1, pageSize: 25 }
|
||||
}
|
||||
|
||||
const Stub = defineComponent({ render: () => h('div') })
|
||||
|
||||
function createTestRouter(): Router {
|
||||
@@ -41,7 +49,7 @@ describe('PackageList.vue', () => {
|
||||
setActivePinia(createPinia())
|
||||
// Prevent real network calls from store actions on mount
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders package list component', async () => {
|
||||
@@ -74,7 +82,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = []
|
||||
setRows(store, [])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('No packages cached yet')
|
||||
@@ -85,7 +93,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -96,17 +104,17 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
expect(wrapper.text()).toContain('1 version')
|
||||
})
|
||||
|
||||
it('calls fetchPackages on mount', async () => {
|
||||
it('asks the server for the first page on mount', async () => {
|
||||
const store = usePackageStore()
|
||||
// beforeEach already spied with mockResolvedValue; reuse that spy
|
||||
const fetchSpy = store.fetchPackages as ReturnType<typeof vi.spyOn>
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
await mountWithRouter()
|
||||
@@ -119,7 +127,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -140,7 +148,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 20,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
@@ -152,7 +160,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -163,7 +171,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
@@ -174,7 +182,17 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '3',
|
||||
registry: 'go',
|
||||
name: 'go-module',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 3,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -195,21 +213,11 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
registry: 'go',
|
||||
name: 'go-module',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 3,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Verify that all registry badges are displayed
|
||||
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
|
||||
// The server sends groups in name order: go-module, npm-package, python-package
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('pypi')
|
||||
expect(wrapper.text()).toContain('go')
|
||||
@@ -223,7 +231,7 @@ describe('PackageList.vue', () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'pypi',
|
||||
@@ -235,7 +243,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2026-11-23T00:00:00Z',
|
||||
download_count: 0,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
@@ -243,4 +251,75 @@ describe('PackageList.vue', () => {
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
describe('server-side paging, search and registry filter', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('debounces the search box into one request with q and page 1', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
const input = wrapper.find('input[type="search"], input')
|
||||
await input.setValue('l')
|
||||
await input.setValue('le')
|
||||
await input.setValue('left')
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'all', q: 'left' })
|
||||
})
|
||||
|
||||
it('sends the registry of the route with every request', async () => {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages/pypi')
|
||||
await router.isReady()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
mount(PackageList, { props: { registry: 'pypi' }, global: { plugins: [router] } })
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'pypi', q: '' })
|
||||
})
|
||||
|
||||
it('pages through the server, not the loaded rows', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.packagePage = {
|
||||
packages: [
|
||||
{ id: '1', registry: 'npm', name: 'a', version: '1', size: 1, cached_at: '2025-01-01T00:00:00Z', last_accessed: '2025-01-01T00:00:00Z', download_count: 0 },
|
||||
],
|
||||
totalGroups: 60,
|
||||
page: 1,
|
||||
pageSize: 25,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.text()).toContain('Page 1 of 3 (60 total packages)')
|
||||
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
|
||||
const next = wrapper.findAll('button').find((b) => /next/i.test(b.attributes('aria-label') ?? b.text()))
|
||||
await next!.trigger('click')
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, pageSize: 25, registry: 'all', q: '' })
|
||||
})
|
||||
|
||||
it('says no packages match when a filter empties the page', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
setRows(store, [])
|
||||
await wrapper.find('input').setValue('zzz')
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
expect(wrapper.text()).not.toContain('No packages cached yet')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="store.fetchPackages()">Refresh</Button>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
@@ -23,32 +23,33 @@
|
||||
variant="card"
|
||||
title="Could not load packages"
|
||||
:message="error"
|
||||
@retry="store.fetchPackages()"
|
||||
@retry="load()"
|
||||
/>
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="packages.length === 0"
|
||||
v-if="totalGroups === 0 && !filtersActive"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages will appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="groupedPackages.length === 0"
|
||||
v-else-if="groups.length === 0"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No packages match"
|
||||
description="Change the registry filter or the search text."
|
||||
/>
|
||||
<Accordion v-else type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groupedPackages"
|
||||
v-for="group in groups"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
: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' : '' }}
|
||||
@@ -109,12 +110,13 @@
|
||||
|
||||
<div v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Page {{ currentPage }} of {{ totalPages }} ({{ allGroupedPackages.length }} total packages)
|
||||
Page {{ currentPage }} of {{ totalPages }} ({{ totalGroups }} total packages)
|
||||
</p>
|
||||
<Pagination
|
||||
:page="currentPage"
|
||||
:total="allGroupedPackages.length"
|
||||
:page-size="itemsPerPage"
|
||||
:total="totalGroups"
|
||||
:page-size="PAGE_SIZE"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
/>
|
||||
</div>
|
||||
@@ -134,7 +136,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, computed, watch } from 'vue'
|
||||
import { onBeforeUnmount, onMounted, ref, computed, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
@@ -177,7 +179,7 @@ const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const { packages, loading, error } = storeToRefs(store)
|
||||
const { packagePage, loading, error } = storeToRefs(store)
|
||||
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
@@ -188,88 +190,77 @@ const REGISTRY_OPTIONS = [
|
||||
{ value: 'go', label: 'Go' },
|
||||
]
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
|
||||
const selectedRegistry = ref<string>(props.registry || 'all')
|
||||
const searchTerm = ref<string>('')
|
||||
// What the server was last asked: the search text lags the input by the debounce.
|
||||
const activeQuery = ref<string>('')
|
||||
const currentPage = ref<number>(1)
|
||||
const itemsPerPage = ref<number>(10)
|
||||
|
||||
// Group packages by name
|
||||
const allGroupedPackages = computed(() => {
|
||||
const groups = new Map<string, Package[]>()
|
||||
const totalGroups = computed(() => packagePage.value.totalGroups)
|
||||
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
|
||||
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
|
||||
|
||||
// Filter packages by selected registry and search term
|
||||
let filteredPackages = selectedRegistry.value === 'all'
|
||||
? packages.value
|
||||
: packages.value.filter(pkg => pkg.registry === selectedRegistry.value)
|
||||
|
||||
// Apply search filter if search term exists
|
||||
if (searchTerm.value.trim()) {
|
||||
const searchLower = searchTerm.value.toLowerCase()
|
||||
filteredPackages = filteredPackages.filter(pkg =>
|
||||
pkg.name.toLowerCase().includes(searchLower) ||
|
||||
displayVersion(pkg).toLowerCase().includes(searchLower) ||
|
||||
pkg.version.toLowerCase().includes(searchLower)
|
||||
)
|
||||
// The server pages whole (registry, name) groups and sends every version row of each.
|
||||
const groups = computed(() => {
|
||||
const byKey = new Map<string, { registry: string; name: string; versions: Package[] }>()
|
||||
for (const pkg of packagePage.value.packages) {
|
||||
const key = `${pkg.registry}\u0000${pkg.name}`
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
group = { registry: pkg.registry, name: pkg.name, versions: [] }
|
||||
byKey.set(key, group)
|
||||
}
|
||||
group.versions.push(pkg)
|
||||
}
|
||||
return Array.from(byKey.values()).map((group) => ({
|
||||
...group,
|
||||
totalSize: group.versions.reduce((sum, v) => sum + v.size, 0),
|
||||
totalDownloads: group.versions.reduce((sum, v) => sum + v.download_count, 0),
|
||||
}))
|
||||
})
|
||||
|
||||
filteredPackages.forEach(pkg => {
|
||||
const key = `${pkg.registry}:${pkg.name}`
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, [])
|
||||
}
|
||||
groups.get(key)!.push(pkg)
|
||||
async function load() {
|
||||
await store.fetchPackagePage({
|
||||
page: currentPage.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
registry: selectedRegistry.value,
|
||||
q: activeQuery.value,
|
||||
})
|
||||
|
||||
// Convert to array and sort versions within each group
|
||||
return Array.from(groups.entries()).map(([key, versions]) => {
|
||||
const [registry, name] = key.split(':')
|
||||
return {
|
||||
registry,
|
||||
name,
|
||||
versions: versions.sort((a, b) =>
|
||||
new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime()
|
||||
),
|
||||
totalSize: versions.reduce((sum, v) => sum + v.size, 0),
|
||||
totalDownloads: versions.reduce((sum, v) => sum + v.download_count, 0),
|
||||
}
|
||||
}).sort((a, b) => a.name.localeCompare(b.name))
|
||||
})
|
||||
|
||||
// Pagination
|
||||
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
|
||||
|
||||
const groupedPackages = computed(() => {
|
||||
const start = (currentPage.value - 1) * itemsPerPage.value
|
||||
const end = start + itemsPerPage.value
|
||||
return allGroupedPackages.value.slice(start, end)
|
||||
})
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
if (page >= 1 && page <= totalPages.value) {
|
||||
currentPage.value = page
|
||||
void load()
|
||||
// Scroll to top of packages list
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
}
|
||||
|
||||
// Reset to page 1 when filters change
|
||||
function resetPagination() {
|
||||
currentPage.value = 1
|
||||
}
|
||||
|
||||
// Watch for filter/search changes and reset pagination
|
||||
watch([selectedRegistry, searchTerm], () => {
|
||||
resetPagination()
|
||||
// A burst of keystrokes asks the server once.
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(searchTerm, (term) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => {
|
||||
if (term === activeQuery.value) return
|
||||
activeQuery.value = term
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
onBeforeUnmount(() => clearTimeout(searchTimer))
|
||||
|
||||
// Watch for route parameter changes to update filter
|
||||
watch(() => route.params.registry, (newRegistry) => {
|
||||
selectedRegistry.value = (newRegistry as string) || 'all'
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await store.fetchPackages()
|
||||
})
|
||||
onMounted(load)
|
||||
|
||||
function confirmDelete(pkg: Package) {
|
||||
packageToDelete.value = pkg
|
||||
@@ -287,7 +278,15 @@ async function deletePackage() {
|
||||
toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
|
||||
store.error = null
|
||||
} else toasts.success('Package deleted', label)
|
||||
} else {
|
||||
toasts.success('Package deleted', label)
|
||||
await load()
|
||||
// Deleting the last group of the last page leaves that page empty.
|
||||
if (packagePage.value.packages.length === 0 && totalGroups.value > 0 && currentPage.value > 1) {
|
||||
currentPage.value = Math.max(totalPages.value, 1)
|
||||
await load()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showVulnerabilityDetails(registry: string, name: string, version: string) {
|
||||
|
||||
@@ -1,18 +1,65 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" :aria-label="label">
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
:key="level"
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="isSelected(level) && 'ring-2 ring-primary'"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
<template #hint>
|
||||
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
|
||||
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
|
||||
{{ packageCounts ? ' · ' : '' }}Filter on
|
||||
</span>
|
||||
</template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
<template v-else>
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
|
||||
import type { VulnerabilityCounts } from '../stores/packages'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
counts: VulnerabilityCounts
|
||||
label: string
|
||||
/** Tiles become toggle buttons that edit `modelValue`. */
|
||||
selectable?: boolean
|
||||
/** Selected severities; several are allowed. */
|
||||
modelValue?: readonly SeverityLevel[]
|
||||
/** Packages per severity, shown on each tile in selectable mode. */
|
||||
packageCounts?: VulnerabilityCounts
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
|
||||
|
||||
function isSelected(level: SeverityLevel): boolean {
|
||||
return props.modelValue?.includes(level) ?? false
|
||||
}
|
||||
|
||||
function toggle(level: SeverityLevel) {
|
||||
const current = props.modelValue ?? []
|
||||
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
|
||||
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
|
||||
}
|
||||
|
||||
function formatPackageCount(n: number): string {
|
||||
return `${n} package${n === 1 ? '' : 's'}`
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -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>
|
||||
@@ -66,6 +70,8 @@
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Registry breakdown</CardTitle>
|
||||
@@ -91,6 +97,8 @@ import { storeToRefs } from 'pinia'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
@@ -103,7 +111,8 @@ import {
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
@@ -162,6 +171,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
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { formatTrendDate, trendValues } from '@/lib/trend'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockReset()
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(props: Record<string, unknown> = {}) {
|
||||
const router = await createTestRouter('/stats')
|
||||
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
|
||||
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
|
||||
|
||||
describe('TrendChart', () => {
|
||||
it('requests the 30 day trend and draws both charts with accessible names', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
|
||||
expect(labels).toHaveLength(2)
|
||||
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
|
||||
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
it('offers every value as text through the chart data table', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tables = wrapper.findAll('table')
|
||||
|
||||
expect(tables.length).toBeGreaterThanOrEqual(2)
|
||||
expect(tables[0]!.text()).toContain('Cached packages')
|
||||
expect(tables[0]!.text()).toContain('4')
|
||||
})
|
||||
|
||||
it('refetches when the period changes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
|
||||
|
||||
await ninety.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
|
||||
})
|
||||
|
||||
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
|
||||
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
|
||||
expect(critical.attributes('aria-pressed')).toBe('false')
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(critical.attributes('aria-pressed')).toBe('true')
|
||||
expect(vulnerable()).toContain('with lines for critical')
|
||||
expect(wrapper.text()).toContain('Critical (highest severity)')
|
||||
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
})
|
||||
|
||||
it('offers all four severities as toggle buttons', async () => {
|
||||
const { wrapper } = await open()
|
||||
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
|
||||
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
|
||||
})
|
||||
|
||||
it('says plainly when vulnerability history starts after the first day', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
|
||||
})
|
||||
|
||||
it('shows no note when every day has vulnerability data', async () => {
|
||||
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: full })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
|
||||
const noScans = {
|
||||
...TREND,
|
||||
vulnerability_history_start: null,
|
||||
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
|
||||
}
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
|
||||
})
|
||||
|
||||
it('shows an empty state when the server holds no snapshots', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows a loading state until the first answer arrives', async () => {
|
||||
let resolve!: (value: unknown) => void
|
||||
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading package history...')
|
||||
resolve({ data: TREND })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).not.toContain('Loading package history...')
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('shows the error with a retry that fetches again', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
const state = wrapper.get('[data-slot="error-state"]')
|
||||
expect(state.text()).toContain('502')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
|
||||
await state.get('button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
expect(requested()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rejects a body without points as an error, not an empty chart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
|
||||
})
|
||||
|
||||
it('ignores an answer that a newer request has replaced', async () => {
|
||||
const answers: Array<(v: unknown) => void> = []
|
||||
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
|
||||
const { wrapper } = await open()
|
||||
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
|
||||
await flushPromises()
|
||||
answers[0]!({ data: TREND })
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
describe('compact', () => {
|
||||
it('always asks for 30 days, draws one chart and links to the full history', async () => {
|
||||
const { wrapper, problems } = await open({ compact: true })
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
|
||||
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
|
||||
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
|
||||
})
|
||||
|
||||
it('says so when the latest day has no vulnerability data', async () => {
|
||||
const last = { ...TREND.points[2]!, vulnerable_packages: null }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
|
||||
const { wrapper } = await open({ compact: true })
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('trend helpers', () => {
|
||||
it('formats a UTC date without shifting it with the viewer zone', () => {
|
||||
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
|
||||
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
|
||||
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
|
||||
})
|
||||
|
||||
it('turns unknown counts into gaps, never zeros', () => {
|
||||
const values = trendValues(TREND.points, 'vulnerable_packages')
|
||||
expect(values[0]).toBeNaN()
|
||||
expect(values.slice(1)).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
<template>
|
||||
<Card data-testid="trend-card">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
|
||||
<CardDescription>
|
||||
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
|
||||
<Button v-else as-child variant="link" size="sm">
|
||||
<RouterLink to="/stats">Open the full history</RouterLink>
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-8">
|
||||
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="inline"
|
||||
title="Could not load the package history"
|
||||
:message="error"
|
||||
@retry="load"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="points.length === 0"
|
||||
title="No history yet"
|
||||
description="The server records the first daily snapshot when it starts, then one more each day."
|
||||
/>
|
||||
<template v-else>
|
||||
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
|
||||
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
|
||||
<LineChart
|
||||
variant="area"
|
||||
:size="compact ? 'sm' : 'md'"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
|
||||
:label="packagesLabel"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
|
||||
{{ compactVulnerable }}
|
||||
</p>
|
||||
|
||||
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
|
||||
<ToggleGroup
|
||||
v-model="severities"
|
||||
type="multiple"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Add a line per highest severity"
|
||||
>
|
||||
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
|
||||
{{ formatSeverityName(level) }}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
|
||||
{{ vulnerabilityNote }}
|
||||
</p>
|
||||
<LineChart
|
||||
v-if="data?.vulnerability_history_start"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="vulnerableSeries"
|
||||
:label="vulnerableLabel"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else
|
||||
size="sm"
|
||||
title="Vulnerability history has not started"
|
||||
description="Scan results are counted from the first daily snapshot that includes them."
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
ToggleGroup,
|
||||
ToggleGroupItem,
|
||||
} from '@perfect-design/ui'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import {
|
||||
DEFAULT_TREND_PERIOD,
|
||||
SEVERITY_LINE_TONES,
|
||||
TREND_PERIODS,
|
||||
formatTrendDate,
|
||||
trendValues,
|
||||
type TrendPeriod,
|
||||
type TrendPoint,
|
||||
type TrendResponse,
|
||||
} from '@/lib/trend'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
|
||||
const severities = ref<SeverityLevel[]>([])
|
||||
const data = ref<TrendResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
let request = 0
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
|
||||
if (current !== request) return
|
||||
const body = response.data as TrendResponse | undefined
|
||||
if (!body || !Array.isArray(body.points)) {
|
||||
data.value = null
|
||||
error.value = 'Unexpected response format from server'
|
||||
return
|
||||
}
|
||||
data.value = body
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
watch(period, load)
|
||||
|
||||
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
|
||||
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
|
||||
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
|
||||
|
||||
function span(key: keyof Omit<TrendPoint, 'date'>): string {
|
||||
const known = points.value.filter((p) => p[key] !== null)
|
||||
const first = known[0]
|
||||
const last = known[known.length - 1]
|
||||
if (!first || !last) return ''
|
||||
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
|
||||
}
|
||||
|
||||
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
|
||||
const vulnerableLabel = computed(() => {
|
||||
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
|
||||
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
|
||||
})
|
||||
|
||||
const vulnerableSeries = computed(() => [
|
||||
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
|
||||
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
|
||||
name: `${formatSeverityName(level)} (highest severity)`,
|
||||
data: values(level),
|
||||
tone: SEVERITY_LINE_TONES[level],
|
||||
})),
|
||||
])
|
||||
|
||||
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
|
||||
const vulnerabilityNote = computed(() => {
|
||||
const start = data.value?.vulnerability_history_start
|
||||
const first = points.value[0]
|
||||
if (!start) return 'Vulnerability history has not started in this period.'
|
||||
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
|
||||
return ''
|
||||
})
|
||||
|
||||
const compactVulnerable = computed(() => {
|
||||
const last = points.value[points.value.length - 1]
|
||||
const n = last?.vulnerable_packages
|
||||
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
|
||||
return `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,226 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
|
||||
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
|
||||
return {
|
||||
id: name,
|
||||
registry: 'npm',
|
||||
name,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2026-01-03T10:00:00Z',
|
||||
last_accessed: '2026-01-03T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: full,
|
||||
total: full.critical + full.high + full.moderate + full.low,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
vulnerable('charlie-moderate', { moderate: 1 }),
|
||||
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
|
||||
]
|
||||
const NAMES = FIXTURE.map((p) => p.name)
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
|
||||
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
|
||||
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
|
||||
const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('VulnerablePackages severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(wrapper.text()).not.toContain('Filter on')
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for vulnerable packages only', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tiles = wrapper.findAll('button[data-severity]')
|
||||
|
||||
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
|
||||
for (const t of tiles) {
|
||||
expect(t.element.tagName).toBe('BUTTON')
|
||||
expect(t.attributes('type')).toBe('button')
|
||||
expect(t.attributes('tabindex')).not.toBe('-1')
|
||||
expect(t.attributes('aria-pressed')).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(['bravo-high'])
|
||||
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
|
||||
expect(tile(wrapper, 'high').text()).toContain('Filter on')
|
||||
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
expect(router.currentRoute.value.query.severity).toBe('high')
|
||||
})
|
||||
|
||||
it('keeps the tile counts of the whole list while a filter is on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const before = tile(wrapper, 'critical').text()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(tile(wrapper, 'critical').text()).toBe(before)
|
||||
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
|
||||
})
|
||||
|
||||
it('selects several severities with OR semantics', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBe('critical,high')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
|
||||
})
|
||||
|
||||
it('a second click toggles the filter off and removes the query', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Clear filters resets every selected severity at once', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
await clearButtons(wrapper)[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
expect(shown(wrapper)).toEqual([])
|
||||
// The tiles stay so the filter can be changed without leaving the page.
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
|
||||
|
||||
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
})
|
||||
@@ -23,7 +23,7 @@
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<Card v-else-if="sortedVulnerablePackages.length === 0">
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
@@ -35,9 +35,34 @@
|
||||
</Card>
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary :counts="totalCounts" label="Vulnerabilities by severity" />
|
||||
<SeveritySummary
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
@@ -104,7 +129,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
@@ -128,12 +153,38 @@ import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
@@ -150,7 +201,8 @@ async function fetchVulnerablePackages() {
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
await store.fetchPackages()
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
@@ -171,9 +223,17 @@ async function fetchVulnerablePackages() {
|
||||
}
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
})
|
||||
|
||||
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
|
||||
const sortedVulnerablePackages = computed(() => {
|
||||
return [...vulnerablePackages.value].sort((a, b) => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
@@ -227,7 +287,18 @@ const groupedPackages = computed(() => {
|
||||
return Array.from(groups.values())
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import Stats from './Stats.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { usePackageStore } from '@/stores/packages'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
@@ -22,6 +22,7 @@ const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
|
||||
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
|
||||
@@ -140,6 +141,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([])
|
||||
@@ -183,6 +209,98 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
|
||||
it('PackageList still fetches through the store on mount', async () => {
|
||||
await smoke(PackageList, '/packages')
|
||||
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
|
||||
expect(usePackageStore().packagePage.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)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { SeverityLevel } from '@/lib/severity'
|
||||
|
||||
export type TrendPeriod = '30day' | '90day' | '1year'
|
||||
|
||||
export const TREND_PERIODS: { value: TrendPeriod; label: string }[] = [
|
||||
{ value: '30day', label: '30 days' },
|
||||
{ value: '90day', label: '90 days' },
|
||||
{ value: '1year', label: '1 year' },
|
||||
]
|
||||
|
||||
export const DEFAULT_TREND_PERIOD: TrendPeriod = '30day'
|
||||
|
||||
/** One UTC day. A null count is unknown (no scan history yet), not zero. */
|
||||
export interface TrendPoint {
|
||||
date: string
|
||||
total_packages: number
|
||||
total_size: number
|
||||
vulnerable_packages: number | null
|
||||
critical: number | null
|
||||
high: number | null
|
||||
moderate: number | null
|
||||
low: number | null
|
||||
blocked: number | null
|
||||
}
|
||||
|
||||
export interface TrendResponse {
|
||||
period: TrendPeriod
|
||||
from: string
|
||||
to: string
|
||||
/** First day in the window with vulnerability data; null when the window has none. */
|
||||
vulnerability_history_start: string | null
|
||||
points: TrendPoint[]
|
||||
}
|
||||
|
||||
/** Chart tone of each severity line, from the LineChart tone set. */
|
||||
export const SEVERITY_LINE_TONES: Record<SeverityLevel, 'danger' | 'warning' | 'info' | 'muted'> = {
|
||||
critical: 'danger',
|
||||
high: 'warning',
|
||||
moderate: 'info',
|
||||
low: 'muted',
|
||||
}
|
||||
|
||||
/** "2026-11-23" as "23 Nov", read in UTC so the label never shifts a day with the viewer's zone. */
|
||||
export function formatTrendDate(iso: string, withYear = false): string {
|
||||
const date = new Date(`${iso}T00:00:00Z`)
|
||||
if (Number.isNaN(date.getTime())) return iso
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: withYear ? 'numeric' : undefined,
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
}
|
||||
|
||||
/** Chart values of one count; unknown days become NaN, which breaks the line instead of drawing zero. */
|
||||
export function trendValues(points: readonly TrendPoint[], key: keyof Omit<TrendPoint, 'date'>): number[] {
|
||||
return points.map((p) => p[key] ?? Number.NaN)
|
||||
}
|
||||
|
||||
/** True when some day in the window has no vulnerability data. */
|
||||
export function hasUnknownVulnerabilityDays(points: readonly TrendPoint[]): boolean {
|
||||
return points.some((p) => p.vulnerable_packages === null)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { usePackageStore, RECENT_PACKAGES, type Package } from './packages'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function pkg(id: number, cachedAt: string, over: Partial<Package> = {}): Package {
|
||||
return {
|
||||
id: String(id),
|
||||
registry: 'npm',
|
||||
name: `p${id}`,
|
||||
version: '1.0.0',
|
||||
size: 1,
|
||||
cached_at: cachedAt,
|
||||
last_accessed: cachedAt,
|
||||
download_count: 0,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('package store paging', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockReset()
|
||||
})
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('sends page, page_size, registry and q; skips the all-registries and empty values', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [], total_groups: 0 } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchPackagePage({ page: 2, pageSize: 25, registry: 'pypi', q: ' six ' })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25, registry: 'all', q: '' })
|
||||
|
||||
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/packages?page=2&page_size=25®istry=pypi&q=six',
|
||||
'/api/packages?page=1&page_size=25',
|
||||
])
|
||||
})
|
||||
|
||||
it('fetchPackages asks for the listed severities only, and for everything without them', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchPackages()
|
||||
await store.fetchPackages({ severity: [] })
|
||||
await store.fetchPackages({ severity: ['critical', 'high'] })
|
||||
|
||||
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/packages',
|
||||
'/api/packages',
|
||||
'/api/packages?severity=critical,high',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the server group count, and counts groups itself when the server sends none', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 80 } })
|
||||
await store.fetchPackagePage({ page: 3, pageSize: 25 })
|
||||
expect(store.packagePage).toMatchObject({ totalGroups: 80, page: 3, pageSize: 25 })
|
||||
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({
|
||||
data: { packages: [pkg(1, '2026-01-01T00:00:00Z'), pkg(1, '2026-01-02T00:00:00Z', { version: '2.0.0' })] },
|
||||
})
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
expect(store.packagePage.totalGroups).toBe(1)
|
||||
})
|
||||
|
||||
it('drops the answer of a request a newer one has replaced', async () => {
|
||||
const store = usePackageStore()
|
||||
let release: (v: unknown) => void = () => {}
|
||||
vi.mocked(axios.get)
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
|
||||
.mockResolvedValueOnce({ data: { packages: [pkg(2, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
|
||||
const slow = store.fetchPackagePage({ page: 1, pageSize: 25, q: 'old' })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25, q: 'new' })
|
||||
release({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
await slow
|
||||
|
||||
expect(store.packagePage.packages.map((p) => p.id)).toEqual(['2'])
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('reports a failed page request and leaves the last page in place', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('502'))
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
|
||||
expect(store.error).toBe('502')
|
||||
expect(store.packagePage.packages).toHaveLength(1)
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('recent packages: small page sorted by cached_at, newest ten rows, newest first', async () => {
|
||||
const rows = Array.from({ length: 14 }, (_, i) => pkg(i, `2026-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`))
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: rows, total_groups: 14 } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchRecentPackages()
|
||||
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(`/api/packages?page=1&page_size=${RECENT_PACKAGES}&sort=cached_at&order=desc`)
|
||||
expect(store.recentPackages).toHaveLength(RECENT_PACKAGES)
|
||||
expect(store.recentPackages[0].id).toBe('13')
|
||||
expect(store.recentPackages[9].id).toBe('4')
|
||||
})
|
||||
|
||||
it('loading stays on until the last overlapping request settles', async () => {
|
||||
const store = usePackageStore()
|
||||
const releases: Array<(v: unknown) => void> = []
|
||||
vi.mocked(axios.get).mockImplementation(() => new Promise((resolve) => releases.push(resolve)))
|
||||
|
||||
const stats = store.fetchStats()
|
||||
const recent = store.fetchRecentPackages()
|
||||
expect(store.loading).toBe(true)
|
||||
releases[0]({ data: { stats: { total_packages: 1 }, registries: {} } })
|
||||
await stats
|
||||
expect(store.loading).toBe(true)
|
||||
releases[1]({ data: { packages: [] } })
|
||||
await recent
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('delete removes one version and leaves reloading to the caller', async () => {
|
||||
vi.mocked(axios.delete).mockResolvedValue({})
|
||||
const store = usePackageStore()
|
||||
await store.deletePackage('npm', 'left-pad', '1.0.0')
|
||||
expect(vi.mocked(axios.delete)).toHaveBeenCalledWith('/api/packages/npm/left-pad/1.0.0')
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+118
-10
@@ -40,20 +40,70 @@ 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 type PackageSort = 'name' | 'cached_at' | 'downloads' | 'size'
|
||||
|
||||
export interface PackagePageParams {
|
||||
page: number
|
||||
pageSize: number
|
||||
/** Empty or 'all' means every registry. */
|
||||
registry?: string
|
||||
/** Case-insensitive match on name, version or release version. */
|
||||
q?: string
|
||||
sort?: PackageSort
|
||||
order?: 'asc' | 'desc'
|
||||
}
|
||||
|
||||
/** One page of package groups: every version row of each group, in group order. */
|
||||
export interface PackagePage {
|
||||
packages: Package[]
|
||||
totalGroups: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** Rows shown under "Recent packages". */
|
||||
export const RECENT_PACKAGES = 10
|
||||
|
||||
function distinctGroups(rows: Package[]): number {
|
||||
return new Set(rows.map((p) => `${p.registry}\u0000${p.name}`)).size
|
||||
}
|
||||
|
||||
export const usePackageStore = defineStore('packages', () => {
|
||||
const packages = ref<Package[]>([])
|
||||
const packagePage = ref<PackagePage>({ packages: [], totalGroups: 0, page: 1, pageSize: 25 })
|
||||
const recentPackages = ref<Package[]>([])
|
||||
const stats = ref<Stats | null>(null)
|
||||
const registries = ref<Record<string, any>>({})
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
async function fetchPackages() {
|
||||
// Requests overlap (stats next to the recent list, a new search before the last answer),
|
||||
// so loading stays on until the last one settles.
|
||||
let inFlight = 0
|
||||
function begin() {
|
||||
inFlight++
|
||||
loading.value = true
|
||||
error.value = null
|
||||
}
|
||||
function settle() {
|
||||
inFlight = Math.max(inFlight - 1, 0)
|
||||
if (inFlight === 0) loading.value = false
|
||||
}
|
||||
let pageRequest = 0
|
||||
|
||||
/**
|
||||
* Every package, unpaginated. Only views that filter on scan results need it.
|
||||
* `severity` keeps the packages whose latest scan has a vulnerability of any listed severity.
|
||||
*/
|
||||
async function fetchPackages(options: { severity?: readonly string[] } = {}) {
|
||||
begin()
|
||||
try {
|
||||
const response = await axios.get('/api/packages')
|
||||
const query = options.severity?.length ? `?severity=${options.severity.join(',')}` : ''
|
||||
const response = await axios.get(`/api/packages${query}`)
|
||||
// Only update packages if we got valid data
|
||||
if (response.data && Array.isArray(response.data.packages)) {
|
||||
packages.value = response.data.packages
|
||||
@@ -66,13 +116,68 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
error.value = err.message
|
||||
// Don't clear packages on error - keep showing the cached data
|
||||
} finally {
|
||||
loading.value = false
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPackagePage(params: PackagePageParams) {
|
||||
const request = ++pageRequest
|
||||
begin()
|
||||
try {
|
||||
const query = new URLSearchParams({ page: String(params.page), page_size: String(params.pageSize) })
|
||||
if (params.registry && params.registry !== 'all') query.set('registry', params.registry)
|
||||
if (params.q?.trim()) query.set('q', params.q.trim())
|
||||
if (params.sort) query.set('sort', params.sort)
|
||||
if (params.order) query.set('order', params.order)
|
||||
const response = await axios.get(`/api/packages?${query.toString()}`)
|
||||
// A newer request is on its way; its answer must win.
|
||||
if (request !== pageRequest) return
|
||||
const data = response.data
|
||||
if (data && Array.isArray(data.packages)) {
|
||||
packagePage.value = {
|
||||
packages: data.packages,
|
||||
totalGroups: Number.isFinite(data.total_groups) ? data.total_groups : distinctGroups(data.packages),
|
||||
page: params.page,
|
||||
pageSize: params.pageSize,
|
||||
}
|
||||
} else {
|
||||
console.warn('Unexpected API response format:', data)
|
||||
error.value = 'Unexpected response format from server'
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (request !== pageRequest) return
|
||||
console.error('Failed to fetch packages:', err)
|
||||
error.value = err.message
|
||||
} finally {
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRecentPackages() {
|
||||
begin()
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`/api/packages?page=1&page_size=${RECENT_PACKAGES}&sort=cached_at&order=desc`,
|
||||
)
|
||||
if (response.data && Array.isArray(response.data.packages)) {
|
||||
// The page holds whole groups, so the newest rows are in there but not in order.
|
||||
recentPackages.value = [...response.data.packages]
|
||||
.sort((a: Package, b: Package) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
|
||||
.slice(0, RECENT_PACKAGES)
|
||||
} else {
|
||||
console.warn('Unexpected API response format:', response.data)
|
||||
error.value = 'Unexpected response format from server'
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch recent packages:', err)
|
||||
error.value = err.message
|
||||
} finally {
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchStats(registry = '') {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
begin()
|
||||
try {
|
||||
const url = registry ? `/api/stats?registry=${registry}` : '/api/stats'
|
||||
const response = await axios.get(url)
|
||||
@@ -89,30 +194,33 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
error.value = err.message
|
||||
// Don't clear stats on error - keep showing the cached data
|
||||
} finally {
|
||||
loading.value = false
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes one version; the caller reloads whichever list it shows. */
|
||||
async function deletePackage(registry: string, name: string, version: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
begin()
|
||||
try {
|
||||
await axios.delete(`/api/packages/${registry}/${name}/${version}`)
|
||||
await fetchPackages()
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
packages,
|
||||
packagePage,
|
||||
recentPackages,
|
||||
stats,
|
||||
registries,
|
||||
loading,
|
||||
error,
|
||||
fetchPackages,
|
||||
fetchPackagePage,
|
||||
fetchRecentPackages,
|
||||
fetchStats,
|
||||
deletePackage,
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
|
||||
@@ -59,6 +60,8 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
|
||||
|
||||
@@ -158,3 +158,19 @@ export const BYPASSES = [
|
||||
active: false,
|
||||
},
|
||||
]
|
||||
|
||||
function trendDay(offset: number): string {
|
||||
return new Date(Date.UTC(2026, 0, 4 + offset)).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export const TREND = {
|
||||
period: '30day',
|
||||
from: trendDay(-2),
|
||||
to: trendDay(0),
|
||||
vulnerability_history_start: trendDay(-1),
|
||||
points: [
|
||||
{ date: trendDay(-2), total_packages: 3, total_size: 3072, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null, blocked: null },
|
||||
{ date: trendDay(-1), total_packages: 4, total_size: 7168, vulnerable_packages: 1, critical: 0, high: 1, moderate: 0, low: 0, blocked: null },
|
||||
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -10,8 +10,10 @@ data:
|
||||
host: {{ .Values.server.host | quote }}
|
||||
port: {{ .Values.server.port }}
|
||||
read_timeout: {{ .Values.server.readTimeout | quote }}
|
||||
read_buffer_size: {{ .Values.server.readBufferSize }}
|
||||
write_timeout: {{ .Values.server.writeTimeout | quote }}
|
||||
idle_timeout: {{ .Values.server.idleTimeout | quote }}
|
||||
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
|
||||
tls:
|
||||
enabled: false
|
||||
|
||||
@@ -73,6 +75,8 @@ data:
|
||||
cache:
|
||||
default_ttl: {{ .Values.cache.defaultTTL | quote }}
|
||||
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
|
||||
idle_ttl: {{ .Values.cache.idleTTL | quote }}
|
||||
deleted_retention: {{ .Values.cache.deletedRetention | default "720h" | quote }}
|
||||
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
|
||||
per_project_quota: {{ .Values.cache.perProjectQuota }}
|
||||
ttl_overrides:
|
||||
|
||||
@@ -91,8 +91,11 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080
|
||||
readTimeout: "5m"
|
||||
readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
writeTimeout: "5m"
|
||||
idleTimeout: "2m"
|
||||
# Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
allowedOrigins: []
|
||||
|
||||
# Additional environment variables for server container
|
||||
# Use this to override config via environment variables
|
||||
@@ -375,14 +378,16 @@ migration:
|
||||
|
||||
# Cache configuration
|
||||
cache:
|
||||
defaultTTL: "168h" # 7 days
|
||||
defaultTTL: "24h" # Freshness window for metadata pages; keep below the 72h client release-age gate
|
||||
cleanupInterval: "1h"
|
||||
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
deletedRetention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
|
||||
maxSizeBytes: 536870912000 # 500GB
|
||||
perProjectQuota: 53687091200 # 50GB
|
||||
ttlOverrides:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
# Security scanning configuration
|
||||
security:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package dbcount counts the SQL statements a GORM handle runs, for query-count tests.
|
||||
package dbcount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Counter holds the number of statements seen since the last Reset.
|
||||
type Counter struct {
|
||||
n atomic.Int64
|
||||
}
|
||||
|
||||
// Attach returns a session of db that counts every statement it executes. It
|
||||
// swaps the logger instead of registering callbacks, because callback
|
||||
// registration is not safe while other goroutines already run queries.
|
||||
// GORM runs a subquery as a dry run with a discarded logger, so subqueries do not count.
|
||||
func Attach(db *gorm.DB) (*gorm.DB, *Counter) {
|
||||
c := &Counter{}
|
||||
return db.Session(&gorm.Session{Logger: &countingLogger{Interface: logger.Discard, c: c}}), c
|
||||
}
|
||||
|
||||
// Reset zeroes the count.
|
||||
func (c *Counter) Reset() { c.n.Store(0) }
|
||||
|
||||
// Count returns the statements counted since the last Reset.
|
||||
func (c *Counter) Count() int { return int(c.n.Load()) }
|
||||
|
||||
type countingLogger struct {
|
||||
logger.Interface
|
||||
c *Counter
|
||||
}
|
||||
|
||||
func (l *countingLogger) LogMode(logger.LogLevel) logger.Interface { return l }
|
||||
|
||||
func (l *countingLogger) Trace(context.Context, time.Time, func() (string, int64), error) {
|
||||
l.c.n.Add(1)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.lake/
|
||||
@@ -0,0 +1,101 @@
|
||||
# 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 |
|
||||
| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e |
|
||||
| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 |
|
||||
| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f |
|
||||
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
|
||||
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
|
||||
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
|
||||
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | this change |
|
||||
|
||||
### 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-17.** A page at any origin issued `DELETE /api/packages/<registry>/<name>/<version>` from a visitor's browser, and
|
||||
`Access-Control-Allow-Origin: *` let it read every `/api` response. Reach: any visitor to a hostile page when
|
||||
`auth.enabled` is false (production); impact is cache eviction. Fixed by `apiOriginGuard` against `server.allowed_origins`;
|
||||
with none set, only same-origin passes.
|
||||
- **GH-19.** An allowed host that answered 302 reached any target (`169.254.169.254`, `127.0.0.1`, `10.x`), by name or by
|
||||
DNS rebinding. No allowed host redirects today; the fix removes the dependency on that. Hops are capped at 10, limited to
|
||||
http(s), vetted against the allowlist, and a hop to another host dials through a guard that refuses private, loopback,
|
||||
link-local and carrier-grade addresses after resolution. A redirect inside one host is left alone: a private index is
|
||||
operator-trusted.
|
||||
- **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.
|
||||
|
||||
### Notes on the fixed rows
|
||||
|
||||
- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry
|
||||
(`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no
|
||||
age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown
|
||||
registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`,
|
||||
`TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`.
|
||||
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
|
||||
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
|
||||
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
|
||||
legacy path. Production holds none.
|
||||
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
|
||||
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
|
||||
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
|
||||
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
|
||||
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
|
||||
source. `TestHandlersSetNoCORSHeaders` and `TestAPIResponsesNeverCarryWildcardOrigin` guard it.
|
||||
|
||||
## 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-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`. |
|
||||
|
||||
### 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,200 @@
|
||||
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, `get`), `pkg/network/client.go` (`send`), `pkg/auth/auth.go` (`ValidateAPIKey` cost), `pkg/app/cors.go` (`apiOriginGuard`), `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
|
||||
|
||||
/-- Before the fix the allowlist was checked once, on the first hop. `network.Client` followed
|
||||
redirects without re-checking, so an allowed host that answers 302 reached any target. -/
|
||||
def hopAllowedOld (hops : List String) : Bool := hops.head?.any hostAllowed
|
||||
|
||||
/-- After the fix (`network.Client.send`, `pypi.Handler.get`) every hop must pass the allowlist. -/
|
||||
def hopAllowed (hops : List String) : Bool := hops.all hostAllowed
|
||||
|
||||
theorem redirect_escapes_allowlist :
|
||||
hopAllowedOld ["files.pythonhosted.org", "169.254.169.254"] = true ∧
|
||||
hostAllowed "169.254.169.254" = false := by decide
|
||||
|
||||
theorem fixed_redirect_stays_allowlisted :
|
||||
hopAllowed ["pypi.org", "files.pythonhosted.org"] = true ∧
|
||||
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = false := by decide
|
||||
|
||||
/-- A hop is accepted only if every hop is on the allowlist. -/
|
||||
theorem hopAllowed_implies_each (hops : List String) (h : hopAllowed hops = true) :
|
||||
∀ x ∈ hops, hostAllowed x = true := by
|
||||
simpa [hopAllowed] using h
|
||||
|
||||
/-! ### API key validation cost (`pkg/auth/auth.go` `ValidateAPIKey`) -/
|
||||
|
||||
/-- bcrypt compares for one request when every stored key is a candidate (before the fix). -/
|
||||
def compareCostOld (storedKeys : ℕ) : ℕ := storedKeys
|
||||
|
||||
/-- A key carrying its id selects one stored key: one compare, hit or miss (a miss compares a dummy hash). -/
|
||||
def compareCostNew (_storedKeys : ℕ) : ℕ := 1
|
||||
|
||||
theorem old_cost_grows_with_keys : compareCostOld 1000 = 1000 := rfl
|
||||
|
||||
theorem new_cost_independent_of_keys (n m : ℕ) : compareCostNew n = compareCostNew m := rfl
|
||||
|
||||
/-! ### Cross-origin writes on `/api` (`pkg/app/cors.go` `apiOriginGuard`) -/
|
||||
|
||||
/-- Before the fix every handler answered `Access-Control-Allow-Origin: *`, so any page could call them. -/
|
||||
def corsOld (_ : Origin) : Bool := true
|
||||
|
||||
/-- After the fix a state-changing request passes iff it names no origin (non-browser client) or an
|
||||
allowed one; the same rule as the WebSocket origin check. -/
|
||||
def writeAllowed (rules : List Origin) : Option Origin → Bool
|
||||
| none => true
|
||||
| some o => rules.any (fun r => matchesExact r o)
|
||||
|
||||
def dashboard : Origin := ⟨Scheme.https, "gohoarder.example.com".toList, none⟩
|
||||
def attacker : Origin := ⟨Scheme.https, "evil.example.net".toList, none⟩
|
||||
|
||||
theorem old_cors_admits_any_page : corsOld attacker = true := rfl
|
||||
|
||||
theorem fixed_refuses_foreign_origin : writeAllowed [dashboard] (some attacker) = false := by decide
|
||||
|
||||
theorem fixed_admits_dashboard_and_cli :
|
||||
writeAllowed [dashboard] (some dashboard) = true ∧ writeAllowed [dashboard] none = true := by decide
|
||||
|
||||
/-- With nothing configured only a request with no origin passes the allowlist step; browsers fall to the
|
||||
same-origin host comparison in the handler. -/
|
||||
theorem empty_allowlist_refuses_any_origin (o : Origin) : writeAllowed [] (some o) = false := by
|
||||
simp [writeAllowed]
|
||||
|
||||
/-! ### 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,84 @@
|
||||
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 and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/
|
||||
theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
|
||||
|
||||
/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but
|
||||
absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/
|
||||
theorem old_default_ttl_exceeded_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⟩
|
||||
|
||||
/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/
|
||||
|
||||
/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/
|
||||
def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default
|
||||
|
||||
/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/
|
||||
theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ)
|
||||
(hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default)
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t :=
|
||||
stale_hides_only_gated gate _ now s t hstale hcfg hnew
|
||||
|
||||
/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/
|
||||
theorem override_replaces_default (default o : ℤ) :
|
||||
effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩
|
||||
|
||||
/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/
|
||||
theorem override_above_gate_breaks_bound :
|
||||
∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧
|
||||
gateAccepts gate now t ∧ gate = 72 := by
|
||||
exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, 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,214 @@
|
||||
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 input (`pkg/cache/cache.go` `store`, `ScanFile`; `scheduleRetry`) -/
|
||||
|
||||
/-- Before the fix a retry reused the first scan's path. Remote storage scans a temp file removed
|
||||
after the first attempt, so only local backends kept it. -/
|
||||
def retryReadableOld (localBackend : Bool) : Bool := localBackend
|
||||
|
||||
/-- After the fix a retry whose file is gone re-reads the blob through the file source. -/
|
||||
def retryReadableNew (localBackend fileSourceSet : Bool) : Bool := localBackend || fileSourceSet
|
||||
|
||||
theorem old_remote_retry_unreadable : retryReadableOld false = false := rfl
|
||||
|
||||
theorem fixed_retry_always_readable : retryReadableNew false true = true ∧ retryReadableNew true false = true := by
|
||||
decide
|
||||
|
||||
/-! ### 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,222 @@
|
||||
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.
|
||||
|
||||
The last three sections model the trend snapshots and backfill in `pkg/metadata/gormstore/snapshots.go`,
|
||||
the soft-delete purge in `pkg/metadata/gormstore/purge.go` and `pkg/cache/cache.go` `purgeDeleted`,
|
||||
and the severity filter in `pkg/metadata/gormstore/dashboard.go`.
|
||||
-/
|
||||
|
||||
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
|
||||
|
||||
/-! ### SQLite upsert (`aggregation_worker.go`, `sqlite_stats.go`) -/
|
||||
|
||||
/-- A bucket is a list of stored rows; the chart sums them. Before the fix SQLite had no unique index,
|
||||
so `INSERT OR REPLACE` appended a row per pass. -/
|
||||
def chartTotal (rows : List ℕ) : ℕ := rows.sum
|
||||
|
||||
/-- Three passes over a bucket whose registry total is 3: three copies. -/
|
||||
theorem old_sqlite_duplicates_rows : chartTotal [3, 3, 3] ≠ 3 := by decide
|
||||
|
||||
/-- `ON CONFLICT ... DO UPDATE` over the unique index keeps one row per bucket: a derived row is set,
|
||||
a package row adds the new events, as on PostgreSQL. -/
|
||||
def upsertDerived (_old new : ℕ) : List ℕ := [new]
|
||||
def upsertAdditive (old new : ℕ) : List ℕ := [old + new]
|
||||
|
||||
theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
|
||||
chartTotal (upsertDerived old new) = new := by simp [chartTotal, upsertDerived]
|
||||
|
||||
theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) :
|
||||
chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive]
|
||||
|
||||
/-! ### Daily snapshots and backfill (`snapshots.go`) -/
|
||||
|
||||
/-- Minutes in a UTC day. -/
|
||||
def dayLen : ℕ := 1440
|
||||
|
||||
/-- `stateAtDayEnd`: a package cached at `cached` and deleted at `x` (`none` = still cached) counts in
|
||||
the snapshot of day `d` iff it was cached before the day ended and not deleted before it ended. -/
|
||||
def aliveAtEnd (cached : ℕ) (deleted : Option ℕ) (d : ℕ) : Prop :=
|
||||
cached < dayLen * (d + 1) ∧ ∀ x, deleted = some x → dayLen * (d + 1) ≤ x
|
||||
|
||||
/-- A package cached and deleted inside one day is in no snapshot. -/
|
||||
theorem same_day_package_never_counted (cached x d : ℕ) (hx : x < dayLen * (d + 1)) :
|
||||
¬ aliveAtEnd cached (some x) d := by
|
||||
rintro ⟨_, h⟩
|
||||
exact absurd (h x rfl) (by omega)
|
||||
|
||||
theorem undeleted_package_counts_from_its_day (cached d : ℕ) :
|
||||
aliveAtEnd cached none d ↔ cached < dayLen * (d + 1) := by
|
||||
simp [aliveAtEnd]
|
||||
|
||||
/-- The backfill adds only each day's change to a running total (`deltas`, then the cumulative loop). -/
|
||||
def delta (s : ℕ → ℤ) (d : ℕ) : ℤ := s d - (if d = 0 then 0 else s (d - 1))
|
||||
|
||||
/-- The running total of the daily changes equals the end-of-day state: the sweep loses nothing. -/
|
||||
theorem sweep_telescopes (s : ℕ → ℤ) (n : ℕ) :
|
||||
∑ d ∈ Finset.range (n + 1), delta s d = s n := by
|
||||
induction n with
|
||||
| zero => simp [delta]
|
||||
| succ n ih =>
|
||||
rw [Finset.sum_range_succ, ih]
|
||||
simp [delta]
|
||||
|
||||
/-- One snapshot row per day, `none` = no row. `upsertSnapshot` (`SnapshotStats`) replaces the day's row. -/
|
||||
def upsertSnapshot (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ := Function.update rows day (some v)
|
||||
|
||||
/-- Running the snapshot twice in a day leaves the last write only. -/
|
||||
theorem snapshot_last_write_wins (rows : ℕ → Option ℕ) (day a b : ℕ) :
|
||||
upsertSnapshot (upsertSnapshot rows day a) day b = upsertSnapshot rows day b :=
|
||||
Function.update_idem _ _ _
|
||||
|
||||
theorem snapshot_leaves_other_days (rows : ℕ → Option ℕ) (day other v : ℕ) (h : other ≠ day) :
|
||||
upsertSnapshot rows day v other = rows other :=
|
||||
Function.update_of_ne h _ _
|
||||
|
||||
/-- The backfill insert (`ON CONFLICT DO NOTHING`) never replaces an existing row. -/
|
||||
def insertMissing (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ :=
|
||||
fun d => if d = day then (rows d).or (some v) else rows d
|
||||
|
||||
theorem backfill_keeps_existing (rows : ℕ → Option ℕ) (day a v : ℕ) (h : rows day = some a) :
|
||||
insertMissing rows day v day = some a := by
|
||||
simp [insertMissing, h]
|
||||
|
||||
/-- The backfill runs only while no past-day snapshot exists, so it cannot rewrite history. -/
|
||||
def backfillRuns (pastRows : ℕ) : Bool := pastRows == 0
|
||||
|
||||
theorem backfill_idle_once_history_exists (n : ℕ) : backfillRuns (n + 1) = false := by
|
||||
simp [backfillRuns]
|
||||
|
||||
/-! ### Soft-delete purge (`purge.go`, `cache.go` `purgeDeleted`) -/
|
||||
|
||||
/-- Cutoff = now - retention; a row is purged iff it was deleted before the cutoff. A row that is
|
||||
not deleted (`none`) is never purged. -/
|
||||
def purgeable (now retention : ℕ) (deleted : Option ℕ) : Prop :=
|
||||
∃ x, deleted = some x ∧ x + retention < now
|
||||
|
||||
theorem active_row_never_purged (now retention : ℕ) : ¬ purgeable now retention none := by
|
||||
rintro ⟨x, h, _⟩
|
||||
cases h
|
||||
|
||||
theorem recent_delete_kept (now retention x : ℕ) (h : now ≤ x + retention) :
|
||||
¬ purgeable now retention (some x) := by
|
||||
rintro ⟨y, hy, hlt⟩
|
||||
cases hy
|
||||
omega
|
||||
|
||||
/-- The purge touches package rows only; the snapshot rows come out as they went in. -/
|
||||
def purgeStep {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
|
||||
List P × (ℕ → Option ℕ) := (pkgs.filter keep, snaps)
|
||||
|
||||
theorem purge_keeps_snapshots {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
|
||||
(purgeStep pkgs keep snaps).2 = snaps := rfl
|
||||
|
||||
/-- One pass purges at most `maxPurgeBatches` batches of `limit` rows. -/
|
||||
def maxPurgeBatches : ℕ := 100
|
||||
|
||||
theorem purge_pass_bounded (batches limit : ℕ) (h : batches ≤ maxPurgeBatches) :
|
||||
batches * limit ≤ maxPurgeBatches * limit :=
|
||||
Nat.mul_le_mul_right limit h
|
||||
|
||||
/-! ### Severity filter (`dashboard.go` `severityFilter`, `latestScanWith`) -/
|
||||
|
||||
/-- A package passes when no severity is selected, or its latest scan counts one of them. -/
|
||||
def passes (selected : List ℕ) (counts : ℕ → ℕ) : Prop := selected = [] ∨ ∃ s ∈ selected, 0 < counts s
|
||||
|
||||
/-- OR semantics: selecting one more severity never hides a package. -/
|
||||
theorem passes_monotone (sel sel' : List ℕ) (counts : ℕ → ℕ) (h : ∀ s ∈ sel, s ∈ sel')
|
||||
(hne : sel ≠ []) (hp : passes sel counts) : passes sel' counts := by
|
||||
right
|
||||
rcases hp with hp | ⟨s, hs, hc⟩
|
||||
· exact absurd hp hne
|
||||
· exact ⟨s, h s hs, hc⟩
|
||||
|
||||
/-- A package with no finding of any selected severity is filtered out. -/
|
||||
theorem clean_package_filtered (sel : List ℕ) (hne : sel ≠ []) : ¬ passes sel (fun _ => 0) := by
|
||||
rintro (h | ⟨s, _, hc⟩)
|
||||
· exact hne h
|
||||
· exact absurd hc (by simp)
|
||||
|
||||
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"
|
||||
@@ -181,6 +181,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
|
||||
FOREIGN KEY (package_id) REFERENCES packages(id) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
|
||||
INDEX idx_scan_package_scanner (package_id, scanner, deleted_at),
|
||||
INDEX idx_scan_package_scanned_at (package_id, scanned_at),
|
||||
INDEX idx_scan_scanned_at (scanned_at DESC),
|
||||
INDEX idx_scan_status (status),
|
||||
INDEX idx_scan_vuln_count (vuln_count)
|
||||
|
||||
@@ -190,6 +190,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
|
||||
);
|
||||
|
||||
CREATE INDEX idx_scan_package_scanner ON scan_results(package_id, scanner) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX idx_scan_package_scanned_at ON scan_results(package_id, scanned_at) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX idx_scan_scanned_at ON scan_results(scanned_at DESC);
|
||||
CREATE INDEX idx_scan_status ON scan_results(status);
|
||||
CREATE INDEX idx_scan_vuln_count ON scan_results(vuln_count) WHERE vuln_count > 0;
|
||||
|
||||
+40
-18
@@ -215,6 +215,10 @@ func (a *App) initializeComponents() error {
|
||||
return fmt.Errorf("failed to initialize scanner: %w", err)
|
||||
}
|
||||
|
||||
if setter, ok := a.metadata.(blockedCounterSetter); ok {
|
||||
setter.SetBlockedCounter(a.countBlocked)
|
||||
}
|
||||
|
||||
// Initialize analytics engine first (needed by cache)
|
||||
log.Info().Msg("Initializing analytics engine")
|
||||
a.analyticsEngine = analytics.NewEngine(analytics.Config{
|
||||
@@ -231,10 +235,13 @@ func (a *App) initializeComponents() error {
|
||||
cleanupInterval = 5 * time.Minute
|
||||
}
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
CleanupInterval: cleanupInterval,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
DeletedRetention: a.config.Cache.DeletedRetention,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize cache: %w", err)
|
||||
@@ -307,10 +314,12 @@ func (a *App) initializeComponents() error {
|
||||
}
|
||||
bootCancel()
|
||||
|
||||
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval)
|
||||
}
|
||||
|
||||
// Initialize WebSocket server
|
||||
@@ -388,10 +397,11 @@ func (a *App) initializeComponents() error {
|
||||
func (a *App) setupServer() error {
|
||||
// Create Fiber app
|
||||
a.app = fiber.New(fiber.Config{
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ReadBufferSize: a.config.Server.ReadBufferSize,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
})
|
||||
|
||||
// Auth middleware factories. Built once, reused on every gated route.
|
||||
@@ -410,6 +420,8 @@ func (a *App) setupServer() error {
|
||||
_ = mwOptional // reserved for future endpoints with anonymous fallback
|
||||
}
|
||||
|
||||
a.app.Use("/api", apiOriginGuard(a.config.Server.AllowedOrigins))
|
||||
|
||||
// Health endpoints — ALWAYS public (k8s liveness/readiness probes).
|
||||
a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler()))
|
||||
a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler()))
|
||||
@@ -439,6 +451,7 @@ func (a *App) setupServer() error {
|
||||
a.app.All("/api/packages/*", mwAuth, a.handlePackages) // OPTIONS, preflight, vulnerabilities
|
||||
a.app.Get("/api/stats", mwAuth, a.handleStats)
|
||||
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
|
||||
a.app.Get("/api/info", mwAuth, a.handleInfo)
|
||||
|
||||
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
|
||||
@@ -453,6 +466,7 @@ func (a *App) setupServer() error {
|
||||
a.app.All("/api/packages/*", a.handlePackages)
|
||||
a.app.Get("/api/stats", a.handleStats)
|
||||
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", a.handleStatsTrend)
|
||||
a.app.Get("/api/info", a.handleInfo)
|
||||
|
||||
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
|
||||
@@ -592,6 +606,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 +627,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)
|
||||
@@ -879,13 +901,13 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
|
||||
}
|
||||
ou, err := url.Parse(origin)
|
||||
if err != nil || ou.Scheme == "" || ou.Host == "" {
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
|
||||
return false
|
||||
}
|
||||
originScheme := strings.ToLower(ou.Scheme)
|
||||
originHost, ok := normalizeOriginHost(originScheme, ou.Host)
|
||||
if !ok {
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -916,7 +938,7 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
|
||||
log.Warn().
|
||||
Str("origin", origin).
|
||||
Str("host", r.Host).
|
||||
Msg("Rejecting WebSocket upgrade: Origin not in allowlist")
|
||||
Msg("Rejecting origin: Origin not in allowlist")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
headerOrigin = "Origin"
|
||||
corsAllowedMethods = "GET, POST, PATCH, DELETE, OPTIONS"
|
||||
corsAllowedHeaders = "Content-Type, Authorization, X-API-Key"
|
||||
corsPreflightMaxAge = "600"
|
||||
headerACRMethod = "Access-Control-Request-Method"
|
||||
headerACAllowOrigin = "Access-Control-Allow-Origin"
|
||||
headerACAllowMethods = "Access-Control-Allow-Methods"
|
||||
headerACAllowHeaders = "Access-Control-Allow-Headers"
|
||||
headerACMaxAge = "Access-Control-Max-Age"
|
||||
)
|
||||
|
||||
// apiOriginGuard enforces server.allowed_origins on /api. A browser at another origin cannot
|
||||
// read responses (no CORS grant) and cannot change state (403), whatever the handlers set.
|
||||
// With nothing configured only the request's own host counts as same-origin.
|
||||
// Requests with neither Origin nor Referer come from non-browser clients and pass.
|
||||
func apiOriginGuard(allowed []string) fiber.Handler {
|
||||
check := buildCheckOrigin(allowed)
|
||||
originAllowed := func(c fiber.Ctx, origin string) bool {
|
||||
r := &http.Request{Header: http.Header{headerOrigin: {origin}}, Host: c.Host()}
|
||||
return check(r)
|
||||
}
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
origin := c.Get(headerOrigin)
|
||||
method := c.Method()
|
||||
|
||||
if method == http.MethodOptions && origin != "" && c.Get(headerACRMethod) != "" {
|
||||
if !originAllowed(c, origin) {
|
||||
return c.SendStatus(fiber.StatusForbidden)
|
||||
}
|
||||
setCORSGrant(c, origin)
|
||||
c.Set(headerACMaxAge, corsPreflightMaxAge)
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
if !isSafeMethod(method) {
|
||||
source := origin
|
||||
if source == "" {
|
||||
source = refererOrigin(c.Get(fiber.HeaderReferer))
|
||||
}
|
||||
if source != "" && !originAllowed(c, source) {
|
||||
log.Warn().Str("method", method).Str("path", c.Path()).Str("origin", source).Msg("Rejecting cross-origin state-changing request")
|
||||
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "cross-origin request not allowed"})
|
||||
}
|
||||
}
|
||||
|
||||
err := c.Next()
|
||||
|
||||
// Drop any grant a handler or upstream set; the allowlist decides.
|
||||
c.Response().Header.Del(headerACAllowOrigin)
|
||||
c.Response().Header.Del(headerACAllowMethods)
|
||||
c.Response().Header.Del(headerACAllowHeaders)
|
||||
c.Vary(headerOrigin)
|
||||
if origin != "" && originAllowed(c, origin) {
|
||||
setCORSGrant(c, origin)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func setCORSGrant(c fiber.Ctx, origin string) {
|
||||
c.Set(headerACAllowOrigin, origin)
|
||||
c.Set(headerACAllowMethods, corsAllowedMethods)
|
||||
c.Set(headerACAllowHeaders, corsAllowedHeaders)
|
||||
c.Vary(headerOrigin)
|
||||
}
|
||||
|
||||
func isSafeMethod(m string) bool {
|
||||
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
|
||||
}
|
||||
|
||||
// refererOrigin returns scheme://host of a Referer, or "" when it is absent or malformed.
|
||||
func refererOrigin(referer string) string {
|
||||
if strings.TrimSpace(referer) == "" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(referer)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return "null" // present but unusable: never matches the allowlist
|
||||
}
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const dashboardOrigin = "https://gohoarder.example.com"
|
||||
|
||||
func seedPackage(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
entry, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*cache.FetchResult, error) {
|
||||
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
}
|
||||
|
||||
func apiCall(t *testing.T, a *App, method, target string, headers map[string]string) *http.Response {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, nil)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
return resp
|
||||
}
|
||||
|
||||
func corsApp(t *testing.T, origins ...string) *App {
|
||||
return newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = origins })
|
||||
}
|
||||
|
||||
const deletePath = "/api/packages/npm/left-pad/1.3.0"
|
||||
|
||||
func TestAPIDeleteFromDisallowedOriginForbidden(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
seedPackage(t, a)
|
||||
|
||||
for _, h := range []map[string]string{
|
||||
{"Origin": "https://evil.example.net"},
|
||||
{"Origin": "null"},
|
||||
{"Referer": "https://evil.example.net/page"},
|
||||
{"Origin": "https://evil.example.net", "Referer": dashboardOrigin + "/x"},
|
||||
} {
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode, "%v", h)
|
||||
}
|
||||
resp := apiCall(t, a, http.MethodGet, "/api/packages/npm", nil)
|
||||
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
|
||||
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
|
||||
assert.NoError(t, err, "a refused request must not delete")
|
||||
}
|
||||
|
||||
func TestAPIDeleteFromAllowedOriginWorks(t *testing.T) {
|
||||
for name, h := range map[string]map[string]string{
|
||||
"origin": {"Origin": dashboardOrigin},
|
||||
"referer": {"Referer": dashboardOrigin + "/packages"},
|
||||
"no-fetch": nil, // curl and server-to-server callers send neither header
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
seedPackage(t, a)
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
|
||||
assert.Error(t, err, "package must be gone")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPostFromDisallowedOriginForbidden(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
resp := apiCall(t, a, http.MethodPost, "/api/admin/prewarming/trigger", map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAPIGetStaysPublicWithoutWildcardCORS(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
|
||||
resp := apiCall(t, a, http.MethodGet, "/api/stats", nil)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
|
||||
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": dashboardOrigin})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, dashboardOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
assert.Contains(t, resp.Header.Values("Vary"), "Origin")
|
||||
|
||||
// Served, but a browser at a foreign origin cannot read it.
|
||||
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
}
|
||||
|
||||
func TestAPIPreflightAnswersOnlyAllowedOrigins(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
preflight := func(origin string) *http.Response {
|
||||
return apiCall(t, a, http.MethodOptions, deletePath, map[string]string{
|
||||
"Origin": origin, "Access-Control-Request-Method": "DELETE",
|
||||
})
|
||||
}
|
||||
|
||||
ok := preflight(dashboardOrigin)
|
||||
assert.Equal(t, http.StatusNoContent, ok.StatusCode)
|
||||
assert.Equal(t, dashboardOrigin, ok.Header.Get("Access-Control-Allow-Origin"))
|
||||
assert.Contains(t, ok.Header.Get("Access-Control-Allow-Methods"), "DELETE")
|
||||
|
||||
bad := preflight("https://evil.example.net")
|
||||
assert.Equal(t, http.StatusForbidden, bad.StatusCode)
|
||||
assert.Empty(t, bad.Header.Get("Access-Control-Allow-Origin"))
|
||||
}
|
||||
|
||||
// With nothing configured, only the host the request was sent to counts as same-origin.
|
||||
func TestAPISameOriginRuleWhenNoOriginsConfigured(t *testing.T) {
|
||||
a := corsApp(t)
|
||||
seedPackage(t, a)
|
||||
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
|
||||
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "http://example.com"}) // httptest.NewRequest Host
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAPIOriginMatchingUsesAllowlistRules(t *testing.T) {
|
||||
a := corsApp(t, "https://*.example.org")
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://ui.example.org"})
|
||||
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
|
||||
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://example.org.evil.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
|
||||
func TestHandlersSetNoCORSHeaders(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
|
||||
continue
|
||||
}
|
||||
parsed, err := parser.ParseFile(fset, f, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", f, err)
|
||||
}
|
||||
ast.Inspect(parsed, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
|
||||
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
|
||||
const dashboard = "https://dash.example.com"
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
|
||||
targets := []string{
|
||||
"/api/stats", "/api/info", "/api/config", "/api/packages",
|
||||
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
|
||||
"/api/analytics/search?q=x", "/api/stats/timeseries",
|
||||
}
|
||||
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
|
||||
for _, target := range targets {
|
||||
hdr := map[string]string{}
|
||||
if origin != "" {
|
||||
hdr["Origin"] = origin
|
||||
}
|
||||
code, h, _ := doRequest(t, a, target, hdr)
|
||||
if code == http.StatusNotFound {
|
||||
t.Errorf("GET %s = 404, route missing", target)
|
||||
}
|
||||
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
|
||||
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func doDelete(t *testing.T, a *App, target string) (int, string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodDelete, target, nil)
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("DELETE %s: %v", target, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return resp.StatusCode, string(body)
|
||||
}
|
||||
|
||||
func TestDeleteMissingPackageIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, target := range []string{
|
||||
"/api/packages/npm/nope/1.0.0",
|
||||
"/api/packages/pypi/nope/1.0.0",
|
||||
"/api/packages/go/example.com/nope/v1.0.0",
|
||||
} {
|
||||
code, body := doDelete(t, a, target)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
|
||||
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExistingPackageIs200(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
|
||||
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
|
||||
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
|
||||
}
|
||||
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
|
||||
t.Errorf("second DELETE = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
+171
-184
@@ -1,12 +1,18 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -14,9 +20,6 @@ import (
|
||||
// handlePackages handles /api/packages endpoint
|
||||
func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -56,156 +59,165 @@ func packageSummary(pkg *metadata.Package) map[string]interface{} {
|
||||
return summary
|
||||
}
|
||||
|
||||
// handleListPackages returns list of cached packages
|
||||
// Pagination limits of GET /api/packages.
|
||||
const (
|
||||
defaultPageSize = 25
|
||||
maxPageSize = 200
|
||||
)
|
||||
|
||||
// listParams are the parsed query parameters of GET /api/packages.
|
||||
type listParams struct {
|
||||
opts metadata.GroupListOptions
|
||||
paged bool
|
||||
}
|
||||
|
||||
// parseSeverities reads a comma-separated severity filter such as "critical,high".
|
||||
func parseSeverities(raw string) ([]string, error) {
|
||||
var out []string
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
sev := strings.ToLower(strings.TrimSpace(part))
|
||||
if sev == "" || slices.Contains(out, sev) {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(metadata.Severities, sev) {
|
||||
return nil, fmt.Errorf("invalid severity %q, must be one of: %s", sev, strings.Join(metadata.Severities, ", "))
|
||||
}
|
||||
out = append(out, sev)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort, order and severity.
|
||||
// Without page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) (listParams, error) {
|
||||
p := listParams{opts: metadata.GroupListOptions{
|
||||
Registry: c.Query("registry"),
|
||||
Query: c.Query("q"),
|
||||
SortBy: metadata.GroupSortName,
|
||||
}}
|
||||
switch sortBy := c.Query("sort"); sortBy {
|
||||
case metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize:
|
||||
p.opts.SortBy = sortBy
|
||||
p.opts.SortDesc = sortBy != metadata.GroupSortName
|
||||
}
|
||||
switch c.Query("order") {
|
||||
case "asc":
|
||||
p.opts.SortDesc = false
|
||||
case "desc":
|
||||
p.opts.SortDesc = true
|
||||
}
|
||||
severities, err := parseSeverities(c.Query("severity"))
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.opts.Severities = severities
|
||||
if c.Query("page") != "" || c.Query("page_size") != "" {
|
||||
p.paged = true
|
||||
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
|
||||
p.opts.PageSize = fiber.Query[int](c, "page_size", defaultPageSize)
|
||||
if p.opts.PageSize < 1 {
|
||||
p.opts.PageSize = defaultPageSize
|
||||
}
|
||||
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
|
||||
func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDecision, error) {
|
||||
if a.scanManager != nil {
|
||||
return a.scanManager.ScanDecisions(ctx, ids)
|
||||
}
|
||||
summaries, err := a.metadata.GetScanSummaries(ctx, ids, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]scanner.ScanDecision, len(summaries))
|
||||
for i, s := range summaries {
|
||||
out[i] = scanner.ScanDecision{Summary: s}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-row scan block of the list payload.
|
||||
func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) map[string]interface{} {
|
||||
if !pkg.SecurityScanned {
|
||||
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false}
|
||||
}
|
||||
d, ok := decisions[pkg.ID]
|
||||
if !ok || !d.Summary.HasScan {
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false}
|
||||
}
|
||||
sum := d.Summary
|
||||
return map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": sum.Status,
|
||||
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
|
||||
"counts": map[string]int{
|
||||
"critical": sum.Critical,
|
||||
"high": sum.High,
|
||||
"moderate": sum.Moderate,
|
||||
"low": sum.Low,
|
||||
},
|
||||
"total": sum.Total,
|
||||
"isBlocked": d.Blocked,
|
||||
}
|
||||
}
|
||||
|
||||
// handleListPackages returns cached packages, one page of groups when page or
|
||||
// page_size is given and every group otherwise.
|
||||
func (a *App) handleListPackages(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
params, err := parseListParams(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
// Get packages from metadata store
|
||||
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
|
||||
Limit: 1000, // Get more to account for duplicates
|
||||
Offset: 0,
|
||||
})
|
||||
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
|
||||
}
|
||||
|
||||
log.Debug().Int("total_packages_from_db", len(allPackages)).Msg("Retrieved packages from database")
|
||||
|
||||
// Filter, clean, and deduplicate packages
|
||||
// Map stores both cleaned package and original name for scan lookups
|
||||
type packageEntry struct {
|
||||
pkg *metadata.Package
|
||||
originalName string
|
||||
response := fiber.Map{
|
||||
"total": len(page.Packages),
|
||||
"total_groups": page.TotalGroups,
|
||||
}
|
||||
seen := make(map[string]*packageEntry)
|
||||
skippedCount := 0
|
||||
for _, pkg := range allPackages {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
skippedCount++
|
||||
log.Debug().
|
||||
Str("name", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("registry", pkg.Registry).
|
||||
Msg("Skipping metadata entry")
|
||||
continue
|
||||
if params.paged {
|
||||
response["page"] = params.opts.Page
|
||||
response["page_size"] = params.opts.PageSize
|
||||
}
|
||||
|
||||
if !a.config.Security.Enabled {
|
||||
response["packages"] = page.Packages
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
var scannedIDs []string
|
||||
for _, pkg := range page.Packages {
|
||||
if pkg.SecurityScanned {
|
||||
scannedIDs = append(scannedIDs, pkg.ID)
|
||||
}
|
||||
|
||||
// Clean the package name (remove /@v/version.ext suffix)
|
||||
originalName := pkg.Name
|
||||
cleanName := pkg.Name
|
||||
if idx := strings.Index(cleanName, "/@v/"); idx != -1 {
|
||||
cleanName = cleanName[:idx]
|
||||
}
|
||||
decisions := map[string]scanner.ScanDecision{}
|
||||
if len(scannedIDs) > 0 {
|
||||
list, err := a.scanDecisions(ctx, scannedIDs)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to load scan summaries")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
|
||||
}
|
||||
|
||||
// Create deduplication key
|
||||
key := cleanName + "@" + pkg.Version
|
||||
|
||||
// Keep the entry with the largest size (typically .zip files)
|
||||
if existing, ok := seen[key]; !ok || pkg.Size > existing.pkg.Size {
|
||||
// Create a copy with cleaned name
|
||||
cleanPkg := *pkg
|
||||
cleanPkg.Name = cleanName
|
||||
seen[key] = &packageEntry{
|
||||
pkg: &cleanPkg,
|
||||
originalName: originalName,
|
||||
}
|
||||
for _, d := range list {
|
||||
decisions[d.Summary.PackageID] = d
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().
|
||||
Int("skipped_metadata", skippedCount).
|
||||
Int("unique_packages", len(seen)).
|
||||
Msg("Filtered and deduplicated packages")
|
||||
|
||||
// Convert map to slice, keeping track of original names
|
||||
type packageWithOriginalName struct {
|
||||
pkg *metadata.Package
|
||||
originalName string
|
||||
enhanced := make([]map[string]interface{}, 0, len(page.Packages))
|
||||
for _, pkg := range page.Packages {
|
||||
pkgMap := packageSummary(pkg)
|
||||
pkgMap["vulnerabilities"] = vulnerabilityInfo(pkg, decisions)
|
||||
enhanced = append(enhanced, pkgMap)
|
||||
}
|
||||
packagesWithNames := make([]packageWithOriginalName, 0, len(seen))
|
||||
for _, entry := range seen {
|
||||
packagesWithNames = append(packagesWithNames, packageWithOriginalName{
|
||||
pkg: entry.pkg,
|
||||
originalName: entry.originalName,
|
||||
})
|
||||
}
|
||||
|
||||
// Enhance packages with vulnerability information if security scanning is enabled
|
||||
var response map[string]interface{}
|
||||
if a.config.Security.Enabled {
|
||||
enhancedPackages := make([]map[string]interface{}, 0, len(packagesWithNames))
|
||||
for _, entry := range packagesWithNames {
|
||||
pkg := entry.pkg
|
||||
pkgMap := packageSummary(pkg)
|
||||
|
||||
// Add vulnerability info if scanned
|
||||
if pkg.SecurityScanned {
|
||||
// Use original name for scan result lookup (handles Go packages with /@v/ suffix)
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, pkg.Registry, entry.originalName, pkg.Version)
|
||||
if err == nil && scanResult != nil {
|
||||
// Count vulnerabilities by severity
|
||||
severityCounts := make(map[string]int)
|
||||
for _, vuln := range scanResult.Vulnerabilities {
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
}
|
||||
|
||||
// Check if package should be blocked based on thresholds
|
||||
isBlocked := false
|
||||
if a.scanManager != nil {
|
||||
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, entry.originalName, pkg.Version)
|
||||
isBlocked = blocked
|
||||
}
|
||||
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": scanResult.Status,
|
||||
"scannedAt": scanResult.ScannedAt.Format(time.RFC3339),
|
||||
"counts": map[string]int{
|
||||
"critical": severityCounts["CRITICAL"],
|
||||
"high": severityCounts["HIGH"],
|
||||
"moderate": severityCounts["MODERATE"],
|
||||
"low": severityCounts["LOW"],
|
||||
},
|
||||
"total": scanResult.VulnerabilityCount,
|
||||
"isBlocked": isBlocked,
|
||||
}
|
||||
} else {
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": false,
|
||||
"status": "pending",
|
||||
"isBlocked": false,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": false,
|
||||
"status": "not_scanned",
|
||||
"isBlocked": false,
|
||||
}
|
||||
}
|
||||
|
||||
enhancedPackages = append(enhancedPackages, pkgMap)
|
||||
}
|
||||
|
||||
response = map[string]interface{}{
|
||||
"packages": enhancedPackages,
|
||||
"total": len(enhancedPackages),
|
||||
}
|
||||
} else {
|
||||
// Non-enhanced mode - just return the packages
|
||||
packages := make([]*metadata.Package, 0, len(packagesWithNames))
|
||||
for _, entry := range packagesWithNames {
|
||||
packages = append(packages, entry.pkg)
|
||||
}
|
||||
response = map[string]interface{}{
|
||||
"packages": packages,
|
||||
"total": len(packages),
|
||||
}
|
||||
}
|
||||
|
||||
// Success response
|
||||
response["packages"] = enhanced
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
@@ -236,7 +248,8 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
if registry == "go" {
|
||||
// List all packages matching the base name and version
|
||||
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
|
||||
Limit: 1000,
|
||||
Registry: registry,
|
||||
NamePrefix: name,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages for deletion")
|
||||
@@ -303,6 +316,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
} else {
|
||||
// For NPM and PyPI, delete directly
|
||||
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
|
||||
var appErr *apperrors.Error
|
||||
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", registry).
|
||||
@@ -342,9 +359,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
// handleStats handles /api/stats endpoint
|
||||
func (a *App) handleStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -363,42 +377,23 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
cacheStats = &metadata.Stats{}
|
||||
}
|
||||
|
||||
// Get all packages to calculate per-registry breakdown
|
||||
packages, err := a.metadata.ListPackages(ctx, nil)
|
||||
registryStats := make(map[string]map[string]interface{})
|
||||
byRegistry, err := a.metadata.GetRegistryStats(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages")
|
||||
packages = []*metadata.Package{}
|
||||
log.Error().Err(err).Msg("Failed to get registry stats")
|
||||
}
|
||||
for _, rs := range byRegistry {
|
||||
registryStats[rs.Registry] = map[string]interface{}{
|
||||
"count": int(rs.Count),
|
||||
"size": rs.Size,
|
||||
"downloads": rs.Downloads,
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate per-registry breakdown and blocked packages count
|
||||
registryStats := make(map[string]map[string]interface{})
|
||||
blockedCount := int64(0)
|
||||
|
||||
for _, pkg := range packages {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Track per-registry stats
|
||||
if _, ok := registryStats[pkg.Registry]; !ok {
|
||||
registryStats[pkg.Registry] = map[string]interface{}{
|
||||
"count": 0,
|
||||
"size": int64(0),
|
||||
"downloads": int64(0),
|
||||
}
|
||||
}
|
||||
registryStats[pkg.Registry]["count"] = registryStats[pkg.Registry]["count"].(int) + 1
|
||||
registryStats[pkg.Registry]["size"] = registryStats[pkg.Registry]["size"].(int64) + pkg.Size
|
||||
registryStats[pkg.Registry]["downloads"] = registryStats[pkg.Registry]["downloads"].(int64) + int64(pkg.DownloadCount)
|
||||
|
||||
// Check if package is blocked (only if security scanning is enabled and package is scanned)
|
||||
if a.config.Security.Enabled && a.scanManager != nil && pkg.SecurityScanned {
|
||||
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if blocked {
|
||||
blockedCount++
|
||||
}
|
||||
}
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
blockedCount, err := a.countBlocked(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
|
||||
// Combine statistics using database stats for accuracy
|
||||
@@ -407,6 +402,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
|
||||
@@ -432,9 +428,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
// Returns time-series download statistics for charts
|
||||
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -474,9 +467,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
// Returns runtime configuration for the frontend
|
||||
func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -508,9 +498,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
// handleInfo handles /api/info endpoint
|
||||
func (a *App) handleInfo(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
|
||||
// handleAdminBypasses handles /api/admin/bypasses endpoint
|
||||
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
// handleAnalyticsTopPackages returns the most downloaded packages
|
||||
func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -31,7 +30,6 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrendingPackages returns trending packages
|
||||
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -52,7 +50,6 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrends returns download trends over time
|
||||
func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
trends := a.analyticsEngine.GetTrends()
|
||||
|
||||
@@ -64,7 +61,6 @@ func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
// handleAnalyticsTotalStats returns overall statistics
|
||||
func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
stats := a.analyticsEngine.GetTotalStats()
|
||||
|
||||
@@ -74,7 +70,6 @@ func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsRegistryStats returns per-registry statistics
|
||||
func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
if registry == "" {
|
||||
@@ -91,7 +86,6 @@ func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsPackageStats returns statistics for a specific package
|
||||
func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
name := c.Params("name")
|
||||
@@ -117,7 +111,6 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsSearch searches for packages matching a query
|
||||
func (a *App) handleAnalyticsSearch(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
query := c.Query("q")
|
||||
if query == "" {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// trendPeriods maps the period query value of /api/stats/trend to days of history.
|
||||
var trendPeriods = map[string]int{"30day": 30, "90day": 90, "1year": 365}
|
||||
|
||||
const defaultTrendPeriod = "30day"
|
||||
|
||||
// handleStatsTrend returns one snapshot per day for the period, oldest first.
|
||||
// Vulnerability fields are null for days before vulnerability history starts.
|
||||
func (a *App) handleStatsTrend(c fiber.Ctx) error {
|
||||
period := c.Query("period", defaultTrendPeriod)
|
||||
days, ok := trendPeriods[period]
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"error": "invalid period, must be one of: 30day, 90day, 1year",
|
||||
})
|
||||
}
|
||||
|
||||
today := time.Now().UTC().Truncate(24 * time.Hour)
|
||||
from := today.AddDate(0, 0, -(days - 1))
|
||||
points, err := a.metadata.GetStatsTrend(c.Context(), from)
|
||||
if err != nil && !errors.Is(err, metadata.ErrNotImplemented) {
|
||||
log.Error().Err(err).Str("period", period).Msg("Failed to get stats trend")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get stats trend"})
|
||||
}
|
||||
if points == nil {
|
||||
points = []*metadata.StatsSnapshot{}
|
||||
}
|
||||
|
||||
var vulnStart *string
|
||||
for _, p := range points {
|
||||
if p.VulnerablePackages != nil {
|
||||
vulnStart = &p.Date
|
||||
break
|
||||
}
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"period": period,
|
||||
"from": from.Format(metadata.StatsSnapshotDateLayout),
|
||||
"to": today.Format(metadata.StatsSnapshotDateLayout),
|
||||
"vulnerability_history_start": vulnStart,
|
||||
"points": points,
|
||||
})
|
||||
}
|
||||
|
||||
// countBlocked counts scanned artifacts the blocking policy refuses.
|
||||
func (a *App) countBlocked(ctx context.Context) (int64, error) {
|
||||
if !a.config.Security.Enabled || a.scanManager == nil {
|
||||
return 0, nil
|
||||
}
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var blocked int64
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blocked++
|
||||
}
|
||||
}
|
||||
return blocked, nil
|
||||
}
|
||||
|
||||
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
|
||||
type blockedCounterSetter interface {
|
||||
SetBlockedCounter(func(context.Context) (int64, error))
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import (
|
||||
// handleVulnerabilities handles /api/packages/{registry}/{name}/{version}/vulnerabilities endpoint
|
||||
func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -45,11 +42,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 +58,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 +91,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 +147,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,144 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
type listResponse struct {
|
||||
Packages []struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Registry string `json:"registry"`
|
||||
Vulnerabilities struct {
|
||||
Status string `json:"status"`
|
||||
IsBlocked bool `json:"isBlocked"`
|
||||
Total int `json:"total"`
|
||||
Counts struct {
|
||||
Critical int `json:"critical"`
|
||||
} `json:"counts"`
|
||||
} `json:"vulnerabilities"`
|
||||
} `json:"packages"`
|
||||
Total int `json:"total"`
|
||||
TotalGroups int `json:"total_groups"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
func getList(t *testing.T, a *App, target string) listResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out listResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestListPackagesPagesGroupsAndAttachesScans(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60)
|
||||
|
||||
page := getList(t, a, "/api/packages?page=2&page_size=25")
|
||||
if page.TotalGroups != 60 || page.Page != 2 || page.PageSize != 25 {
|
||||
t.Fatalf("paging fields = %+v", page)
|
||||
}
|
||||
if len(page.Packages) != 25 || page.Total != 25 {
|
||||
t.Fatalf("page 2 holds %d rows (total %d), want 25", len(page.Packages), page.Total)
|
||||
}
|
||||
if first := page.Packages[0].Name; first != "pkg-025" {
|
||||
t.Errorf("page 2 starts at %q, want pkg-025 (name order)", first)
|
||||
}
|
||||
|
||||
last := getList(t, a, "/api/packages?page=3&page_size=25")
|
||||
if len(last.Packages) != 10 {
|
||||
t.Errorf("last page holds %d rows, want 10", len(last.Packages))
|
||||
}
|
||||
|
||||
found := getList(t, a, "/api/packages?q=PKG-005&page_size=10")
|
||||
if found.TotalGroups != 1 || len(found.Packages) != 1 {
|
||||
t.Fatalf("search pkg-005 = %+v", found)
|
||||
}
|
||||
v := found.Packages[0].Vulnerabilities
|
||||
if v.Status != "vulnerable" || !v.IsBlocked || v.Total != 1 || v.Counts.Critical != 1 {
|
||||
t.Errorf("pkg-005 scan block = %+v, want vulnerable, blocked, one critical", v)
|
||||
}
|
||||
|
||||
clean := getList(t, a, "/api/packages?q=pkg-006&page_size=10")
|
||||
if cv := clean.Packages[0].Vulnerabilities; cv.Status != "clean" || cv.IsBlocked {
|
||||
t.Errorf("pkg-006 scan block = %+v, want clean and not blocked", cv)
|
||||
}
|
||||
|
||||
if none := getList(t, a, "/api/packages?registry=pypi&page_size=10"); none.TotalGroups != 0 || len(none.Packages) != 0 {
|
||||
t.Errorf("pypi filter = %+v, want empty", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPackagesRecentFirst(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 30)
|
||||
recent := getList(t, a, "/api/packages?sort=cached_at&order=desc&page=1&page_size=3")
|
||||
got := []string{recent.Packages[0].Name, recent.Packages[1].Name, recent.Packages[2].Name}
|
||||
want := []string{"pkg-000", "pkg-001", "pkg-002"} // seedScanned caches pkg-N N minutes ago
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("recent = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The unpaginated list used to stop at 1000 rows without saying so.
|
||||
func TestListPackagesUnpaginatedHasNoCap(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
const rows = 1005
|
||||
now := time.Now()
|
||||
for i := 0; i < rows; i++ {
|
||||
name := fmt.Sprintf("bulk-%04d", i)
|
||||
if err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
}
|
||||
all := getList(t, a, "/api/packages")
|
||||
if len(all.Packages) != rows || all.Total != rows || all.TotalGroups != rows {
|
||||
t.Fatalf("unpaginated list = %d rows, total %d, groups %d; want %d", len(all.Packages), all.Total, all.TotalGroups, rows)
|
||||
}
|
||||
if capped := getList(t, a, "/api/packages?page_size=100000"); capped.PageSize != maxPageSize || len(capped.Packages) != maxPageSize {
|
||||
t.Errorf("page_size clamp: size %d, rows %d, want %d", capped.PageSize, len(capped.Packages), maxPageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsFromAggregates(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60)
|
||||
code, _, body := doRequest(t, a, "/api/stats", nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("GET /api/stats = %d %s", code, body)
|
||||
}
|
||||
var out struct {
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Registries map[string]map[string]float64 `json:"registries"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Stats["total_packages"] != 60 || out.Stats["scanned_packages"] != 60 || out.Stats["vulnerable_packages"] != 12 {
|
||||
t.Errorf("stats = %v", out.Stats)
|
||||
}
|
||||
if out.Stats["blocked_packages"] != 12 {
|
||||
t.Errorf("blocked_packages = %v, want the 12 critical packages", out.Stats["blocked_packages"])
|
||||
}
|
||||
if npm := out.Registries["npm"]; npm["count"] != 60 || npm["size"] != 6000 {
|
||||
t.Errorf("npm registry = %v, want 60 rows and 6000 bytes", npm)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// newTestApp builds a full App on temp storage with the given config tweaks.
|
||||
@@ -284,3 +286,33 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
|
||||
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = upstream.URL
|
||||
c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute}
|
||||
})
|
||||
if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %q", code, body)
|
||||
}
|
||||
|
||||
pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range pkgs {
|
||||
if p.ExpiresAt == nil {
|
||||
continue
|
||||
}
|
||||
if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute {
|
||||
t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// seedScanned stores n scanned npm packages, every fifth with a critical finding.
|
||||
func seedScanned(t *testing.T, a *App, from, n int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for i := from; i < from+n; i++ {
|
||||
name := fmt.Sprintf("pkg-%03d", i)
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name + "/1.0.0",
|
||||
Size: 100, CachedAt: now.Add(-time.Duration(i) * time.Minute), LastAccessed: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
res := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "test",
|
||||
Status: metadata.ScanStatusClean, ScannedAt: now,
|
||||
}
|
||||
if i%5 == 0 {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.VulnerabilityCount = 1
|
||||
res.Vulnerabilities = []metadata.Vulnerability{{ID: fmt.Sprintf("CVE-2026-%04d", i), Severity: "critical"}}
|
||||
}
|
||||
if err := a.metadata.SaveScanResult(ctx, res); err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newScanningApp(t *testing.T) (*App, *dbcount.Counter) {
|
||||
t.Helper()
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.Scanners.Static.Enabled = false
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
})
|
||||
store, ok := a.metadata.(*gormstore.GORMStoreV2)
|
||||
if !ok {
|
||||
t.Fatalf("metadata store is %T, want *gormstore.GORMStoreV2", a.metadata)
|
||||
}
|
||||
var counter *dbcount.Counter
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
return a, counter
|
||||
}
|
||||
|
||||
// queriesFor reports how many SQL statements one GET runs.
|
||||
func queriesFor(t *testing.T, a *App, c *dbcount.Counter, target string) int {
|
||||
t.Helper()
|
||||
c.Reset()
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
return c.Count()
|
||||
}
|
||||
|
||||
// The dashboard endpoints must cost the same number of statements for 20 rows and for 120.
|
||||
func TestDashboardEndpointsQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{"/api/packages", "/api/packages?page=1&page_size=25", "/api/stats"}
|
||||
|
||||
seedScanned(t, a, 0, 20)
|
||||
small := map[string]int{}
|
||||
for _, target := range targets {
|
||||
small[target] = queriesFor(t, a, counter, target)
|
||||
}
|
||||
|
||||
seedScanned(t, a, 20, 100)
|
||||
for _, target := range targets {
|
||||
large := queriesFor(t, a, counter, target)
|
||||
t.Logf("%-40s 20 rows: %3d queries, 120 rows: %3d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows; the count must not grow with rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
const recentPackagesURL = "/api/packages?page=1&page_size=10&sort=cached_at&order=desc"
|
||||
|
||||
// Fiber v3 defaults to an 8192-byte read buffer; OIDC session cookies plus a long Referer exceed it.
|
||||
func TestLargeRequestHeadersAreAccepted(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
headers := map[string]string{
|
||||
"Cookie": "session=" + strings.Repeat("a", 5000),
|
||||
"Referer": "https://dash.example.com/" + strings.Repeat("r", 5000),
|
||||
}
|
||||
code, _, body := doRequest(t, a, recentPackagesURL, headers)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET with ~10KB of headers = %d %q, want 200", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadBufferSizeIsConfigurable(t *testing.T) {
|
||||
if got := config.Default().Server.ReadBufferSize; got != 16384 {
|
||||
t.Fatalf("default server.read_buffer_size = %d, want 16384", got)
|
||||
}
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.ReadBufferSize = 4096 })
|
||||
req := httptest.NewRequest(http.MethodGet, recentPackagesURL, nil)
|
||||
req.Header.Set("Cookie", "session="+strings.Repeat("a", 6000))
|
||||
if _, err := a.app.Test(req); err == nil || !strings.Contains(err.Error(), "small read buffer") {
|
||||
t.Errorf("6KB header with a 4096 buffer: err = %v, want a small-read-buffer rejection", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeverityFilterOnPackagesList(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60) // every fifth package carries one critical finding
|
||||
|
||||
cases := []struct {
|
||||
query string
|
||||
want int
|
||||
}{
|
||||
{"", 60},
|
||||
{"?severity=", 60},
|
||||
{"?severity=critical", 12},
|
||||
{"?severity=Critical,high", 12},
|
||||
{"?severity=high", 0},
|
||||
{"?severity=high,moderate,low", 0},
|
||||
{"?severity=critical&q=pkg-005", 1},
|
||||
{"?severity=critical&q=pkg-006", 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := getList(t, a, "/api/packages"+c.query); len(got.Packages) != c.want {
|
||||
t.Errorf("%q returned %d packages, want %d", c.query, len(got.Packages), c.want)
|
||||
}
|
||||
}
|
||||
|
||||
paged := getList(t, a, "/api/packages?severity=critical&page=1&page_size=5")
|
||||
if paged.TotalGroups != 12 || len(paged.Packages) != 5 {
|
||||
t.Errorf("paged severity list = %d groups, %d rows; want 12 groups, 5 rows", paged.TotalGroups, len(paged.Packages))
|
||||
}
|
||||
for _, p := range getList(t, a, "/api/packages?severity=critical").Packages {
|
||||
if p.Vulnerabilities.Counts.Critical == 0 {
|
||||
t.Errorf("%s has no critical finding but passed the critical filter", p.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeverityFilterRejectsUnknownValue(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
for _, q := range []string{"?severity=urgent", "?severity=critical,nope"} {
|
||||
if code, _, body := doRequest(t, a, "/api/packages"+q, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("%q = %d %s, want 400", q, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func listTree(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
err := filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
names = append(names, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Join(names, "\n")
|
||||
}
|
||||
|
||||
// Shutdown must leave nothing running against the data directory: a late SQLite close deletes
|
||||
// its -wal/-shm files after Shutdown returned and breaks the removal of the directory.
|
||||
func TestShutdownLeavesDataDirectoryStable(t *testing.T) {
|
||||
for i := 0; i < 40; i++ {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.Storage.Backend = "filesystem"
|
||||
cfg.Storage.Path = filepath.Join(dir, "store")
|
||||
cfg.Metadata.Backend = "sqlite"
|
||||
cfg.Metadata.SQLite.Path = filepath.Join(dir, "meta", "meta.db")
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.Metadata.SQLite.Path), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Security.Enabled = false
|
||||
cfg.Prewarming.Enabled = false
|
||||
cfg.Auth.Enabled = false
|
||||
a, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
doRequest(t, a, "/api/stats", nil)
|
||||
if err := a.Shutdown(); err != nil {
|
||||
t.Fatalf("Shutdown: %v", err)
|
||||
}
|
||||
before := listTree(t, dir)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if after := listTree(t, dir); before != after {
|
||||
t.Fatalf("iteration %d: data directory changed after Shutdown:\nbefore:\n%s\nafter:\n%s", i, before, after)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
)
|
||||
|
||||
type trendResponse struct {
|
||||
VulnerabilityHistoryStart *string `json:"vulnerability_history_start"`
|
||||
Period string `json:"period"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Points []struct {
|
||||
VulnerablePackages *int64 `json:"vulnerable_packages"`
|
||||
Blocked *int64 `json:"blocked"`
|
||||
Date string `json:"date"`
|
||||
TotalPackages int64 `json:"total_packages"`
|
||||
} `json:"points"`
|
||||
}
|
||||
|
||||
func trendDay(daysAgo int) string {
|
||||
return time.Now().UTC().AddDate(0, 0, -daysAgo).Format("2006-01-02")
|
||||
}
|
||||
|
||||
func getTrend(t *testing.T, a *App, target string) trendResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out trendResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeverityAndTrendQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{
|
||||
"/api/packages?severity=critical,high",
|
||||
"/api/packages?severity=low&page=1&page_size=25",
|
||||
"/api/stats/trend?period=90day",
|
||||
}
|
||||
seedScanned(t, a, 0, 20)
|
||||
small := map[string]int{}
|
||||
for _, target := range targets {
|
||||
small[target] = queriesFor(t, a, counter, target)
|
||||
}
|
||||
seedScanned(t, a, 20, 100)
|
||||
for _, target := range targets {
|
||||
large := queriesFor(t, a, counter, target)
|
||||
t.Logf("%-50s 20 rows: %2d queries, 120 rows: %2d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
if n := small["/api/stats/trend?period=90day"]; n != 1 {
|
||||
t.Errorf("trend costs %d statements, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendEndpoint(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
empty := getTrend(t, a, "/api/stats/trend")
|
||||
if empty.Period != "30day" || empty.Points == nil || len(empty.Points) != 0 || empty.VulnerabilityHistoryStart != nil {
|
||||
t.Fatalf("empty trend = %+v, want the default period, no points and no vulnerability start", empty)
|
||||
}
|
||||
|
||||
store := a.metadata.(*gormstore.GORMStoreV2)
|
||||
one, two := int64(1), int64(2)
|
||||
for _, row := range []gormstore.StatsSnapshotModel{
|
||||
{Day: trendDay(100), TotalPackages: 5},
|
||||
{Day: trendDay(40), TotalPackages: 6},
|
||||
{Day: trendDay(2), TotalPackages: 7},
|
||||
{Day: trendDay(1), TotalPackages: 8, VulnerablePackages: &two, Blocked: &one},
|
||||
} {
|
||||
if err := store.DB().Create(&row).Error; err != nil {
|
||||
t.Fatalf("seed snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
target string
|
||||
period string
|
||||
points int
|
||||
}{
|
||||
{"/api/stats/trend", "30day", 2},
|
||||
{"/api/stats/trend?period=30day", "30day", 2},
|
||||
{"/api/stats/trend?period=90day", "90day", 3},
|
||||
{"/api/stats/trend?period=1year", "1year", 4},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := getTrend(t, a, c.target)
|
||||
if got.Period != c.period || len(got.Points) != c.points {
|
||||
t.Errorf("%s = period %q, %d points; want %q, %d", c.target, got.Period, len(got.Points), c.period, c.points)
|
||||
}
|
||||
}
|
||||
|
||||
got := getTrend(t, a, "/api/stats/trend")
|
||||
if got.To != trendDay(0) || got.From != trendDay(29) {
|
||||
t.Errorf("window = %s..%s, want %s..%s", got.From, got.To, trendDay(29), trendDay(0))
|
||||
}
|
||||
if got.Points[0].Date != trendDay(2) || got.Points[1].Date != trendDay(1) {
|
||||
t.Errorf("points not oldest first: %+v", got.Points)
|
||||
}
|
||||
if got.Points[0].VulnerablePackages != nil || got.Points[0].Blocked != nil {
|
||||
t.Errorf("a day without vulnerability data must carry null, got %+v", got.Points[0])
|
||||
}
|
||||
if v := got.Points[1].VulnerablePackages; v == nil || *v != 2 {
|
||||
t.Errorf("vulnerable_packages = %v, want 2", v)
|
||||
}
|
||||
if got.VulnerabilityHistoryStart == nil || *got.VulnerabilityHistoryStart != trendDay(1) {
|
||||
t.Errorf("vulnerability_history_start = %v, want %s", got.VulnerabilityHistoryStart, trendDay(1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendRejectsUnknownPeriod(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, p := range []string{"7day", "1day", "bogus", "1YEAR"} {
|
||||
if code, _, body := doRequest(t, a, "/api/stats/trend?period="+p, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("period=%s = %d %s, want 400", p, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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)
|
||||
|
||||
// Bursts stay under the 256-slot channel and wait for the loop to drain between them, so the
|
||||
// result depends on the loop running, not on how fast the scheduler runs it.
|
||||
const (
|
||||
bursts = 10
|
||||
burstLen = 100
|
||||
)
|
||||
for b := 0; b < bursts; b++ {
|
||||
for i := 0; i < burstLen; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for a.wsServer.Pending() > 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(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, bursts*burstLen)
|
||||
}
|
||||
}
|
||||
+107
-31
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/base64"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -154,10 +155,12 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to generate random key")
|
||||
}
|
||||
|
||||
rawKey := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
secret := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
id := keyPrefix + generateID()
|
||||
rawKey := id + keySeparator + secret
|
||||
|
||||
// Hash the key with the configured cost.
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), m.cfg.BcryptCost)
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(secret), m.cfg.BcryptCost)
|
||||
if err != nil {
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key")
|
||||
}
|
||||
@@ -169,7 +172,7 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
}
|
||||
|
||||
apiKey := &APIKey{
|
||||
ID: generateID(),
|
||||
ID: id,
|
||||
Name: name,
|
||||
HashedKey: string(hashedKey),
|
||||
Role: role,
|
||||
@@ -198,46 +201,119 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
return apiKey, rawKey, nil
|
||||
}
|
||||
|
||||
// Key format: "<id>.<secret>" with id "ghk_<random>". The id is public and selects one stored
|
||||
// key; the bcrypt hash covers the secret only. Keys minted before the format
|
||||
// existed have no id in the raw key and hash the whole raw key.
|
||||
const (
|
||||
keyPrefix = "ghk_"
|
||||
keySeparator = "."
|
||||
// maxLegacyCompares bounds concurrent bcrypt checks against pre-id keys,
|
||||
// which can only be found by trying each one.
|
||||
maxLegacyCompares = 4
|
||||
// legacyIDLen is the length of base64url(16 bytes).
|
||||
legacyIDLen = 24
|
||||
)
|
||||
|
||||
var (
|
||||
bcryptCompare = bcrypt.CompareHashAndPassword
|
||||
legacySlots = make(chan struct{}, maxLegacyCompares)
|
||||
// dummyHash keeps the cost of an unknown id equal to a wrong secret.
|
||||
dummyHash = mustHash("gohoarder-dummy-secret")
|
||||
)
|
||||
|
||||
func mustHash(s string) []byte {
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("auth: dummy hash: %v", err))
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// ValidateAPIKey validates an API key and returns the associated key object.
|
||||
// Hot path: snapshots candidates, runs bcrypt without holding the lock.
|
||||
// LastUsedAt is updated in-memory under the write lock and flushed to the
|
||||
// store via a fire-and-forget goroutine.
|
||||
// A key with an id costs exactly one bcrypt compare, whatever the number of
|
||||
// stored keys. LastUsedAt is updated in-memory under the write lock and
|
||||
// flushed to the store via a fire-and-forget goroutine.
|
||||
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) {
|
||||
// Phase 1: snapshot non-expired candidates under RLock. We hold pointers
|
||||
// to APIKey; APIKey.HashedKey is an immutable string so reading it
|
||||
// without a lock is safe even if the key is later removed from the map.
|
||||
var apiKey *APIKey
|
||||
if id, secret, ok := splitKey(rawKey); ok {
|
||||
apiKey = m.validateByID(id, secret)
|
||||
} else {
|
||||
apiKey = m.validateLegacy(ctx, rawKey)
|
||||
}
|
||||
if apiKey == nil {
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
}
|
||||
|
||||
// Re-check the key still exists to avoid resurrecting a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
func splitKey(rawKey string) (id, secret string, ok bool) {
|
||||
if !strings.HasPrefix(rawKey, keyPrefix) {
|
||||
return "", "", false
|
||||
}
|
||||
return strings.Cut(rawKey, keySeparator)
|
||||
}
|
||||
|
||||
// hasKeyID reports whether k was minted with an id embedded in its raw key.
|
||||
// Legacy ids are bare generateID output, which is always legacyIDLen long.
|
||||
func hasKeyID(k *APIKey) bool {
|
||||
return strings.HasPrefix(k.ID, keyPrefix) && len(k.ID) > legacyIDLen
|
||||
}
|
||||
|
||||
func (m *Manager) validateByID(id, secret string) *APIKey {
|
||||
m.mu.RLock()
|
||||
apiKey := m.keys[id]
|
||||
m.mu.RUnlock()
|
||||
|
||||
hash := dummyHash
|
||||
if apiKey != nil {
|
||||
hash = []byte(apiKey.HashedKey)
|
||||
}
|
||||
err := bcryptCompare(hash, []byte(secret))
|
||||
if apiKey == nil || err != nil || expired(apiKey, time.Now()) {
|
||||
return nil
|
||||
}
|
||||
return apiKey
|
||||
}
|
||||
|
||||
func (m *Manager) validateLegacy(ctx context.Context, rawKey string) *APIKey {
|
||||
m.mu.RLock()
|
||||
candidates := make([]*APIKey, 0, len(m.keys))
|
||||
now := time.Now()
|
||||
for _, apiKey := range m.keys {
|
||||
if apiKey.ExpiresAt != nil && now.After(*apiKey.ExpiresAt) {
|
||||
continue
|
||||
for _, k := range m.keys {
|
||||
if !hasKeyID(k) && !expired(k, now) {
|
||||
candidates = append(candidates, k)
|
||||
}
|
||||
candidates = append(candidates, apiKey)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
// Phase 2: run bcrypt comparisons without holding any lock so concurrent
|
||||
// auth checks can proceed in parallel.
|
||||
for _, apiKey := range candidates {
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(apiKey.HashedKey), []byte(rawKey)); err == nil {
|
||||
// Phase 3: briefly take the write lock to update LastUsedAt.
|
||||
// Re-check the key still exists in the map to avoid resurrecting
|
||||
// a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
for _, k := range candidates {
|
||||
select {
|
||||
case legacySlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
err := bcryptCompare([]byte(k.HashedKey), []byte(rawKey))
|
||||
<-legacySlots
|
||||
if err == nil {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
func expired(k *APIKey, now time.Time) bool {
|
||||
return k.ExpiresAt != nil && now.After(*k.ExpiresAt)
|
||||
}
|
||||
|
||||
// persistLastUsedAsync flushes a LastUsedAt update to the store off the hot
|
||||
|
||||
+25
-1
@@ -116,6 +116,15 @@ func (f *fakeStore) DeletePackage(context.Context, string, string, string) error
|
||||
func (f *fakeStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ListPackageGroups(context.Context, metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetScanSummaries(context.Context, []string, bool) ([]*metadata.ScanSummary, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetRegistryStats(context.Context) ([]metadata.RegistryStat, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) UpdateDownloadCount(context.Context, string, string, string) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
@@ -147,7 +156,22 @@ 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) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, 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} }
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// countBcrypt wraps bcryptCompare and returns the call counter.
|
||||
func countBcrypt(t *testing.T) *atomic.Int64 {
|
||||
t.Helper()
|
||||
var n atomic.Int64
|
||||
orig := bcryptCompare
|
||||
bcryptCompare = func(h, p []byte) error {
|
||||
n.Add(1)
|
||||
return orig(h, p)
|
||||
}
|
||||
t.Cleanup(func() { bcryptCompare = orig })
|
||||
return &n
|
||||
}
|
||||
|
||||
func newTestManager() *Manager { return NewWithStore(Config{BcryptCost: bcrypt.MinCost}, nil) }
|
||||
|
||||
// addLegacyKey stores a key in the pre-key-id format: bcrypt of the whole raw key, no id in the key.
|
||||
func addLegacyKey(t *testing.T, m *Manager) string {
|
||||
t.Helper()
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
raw := base64.URLEncoding.EncodeToString(b)
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
k := &APIKey{ID: generateID(), Name: "legacy", HashedKey: string(h), Role: RoleReadOnly, CreatedAt: time.Now(), Permissions: getPermissionsForRole(RoleReadOnly)}
|
||||
m.mu.Lock()
|
||||
m.keys[k.ID] = k
|
||||
m.mu.Unlock()
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestValidateAPIKeyCostIndependentOfKeyCount(t *testing.T) {
|
||||
m := newTestManager()
|
||||
_, good, err := m.GenerateAPIKey("target", RoleReadWrite, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 50; i++ {
|
||||
if _, _, err := m.GenerateAPIKey("filler", RoleReadOnly, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
n := countBcrypt(t)
|
||||
|
||||
if _, err := m.ValidateAPIKey(context.Background(), good); err != nil {
|
||||
t.Fatalf("valid key rejected: %v", err)
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("valid key: %d bcrypt compares, want 1", got)
|
||||
}
|
||||
|
||||
n.Store(0)
|
||||
idPart := strings.SplitN(good, keySeparator, 2)[0]
|
||||
cases := map[string]string{
|
||||
"known id, wrong secret": idPart + keySeparator + "AAAA",
|
||||
"unknown id": keyPrefix + "nope" + keySeparator + "AAAA",
|
||||
"no secret": idPart + keySeparator,
|
||||
}
|
||||
for name, raw := range cases {
|
||||
n.Store(0)
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("%s: %d bcrypt compares, want exactly 1", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAPIKeyRejectsSecretOfAnotherKey(t *testing.T) {
|
||||
m := newTestManager()
|
||||
a, _, _ := m.GenerateAPIKey("a", RoleAdmin, nil)
|
||||
_, rawB, _ := m.GenerateAPIKey("b", RoleReadOnly, nil)
|
||||
secretB := strings.SplitN(rawB, keySeparator, 2)[1]
|
||||
if _, err := m.ValidateAPIKey(context.Background(), a.ID+keySeparator+secretB); err == nil {
|
||||
t.Fatal("id of one key with the secret of another was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyKeysStillValidate(t *testing.T) {
|
||||
m := newTestManager()
|
||||
raw := addLegacyKey(t, m)
|
||||
for i := 0; i < 3; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
k, err := m.ValidateAPIKey(context.Background(), raw)
|
||||
if err != nil || k == nil || k.Name != "legacy" {
|
||||
t.Fatalf("legacy key rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFormatKeyNeverTouchesLegacyKeys(t *testing.T) {
|
||||
m := newTestManager()
|
||||
for i := 0; i < 20; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
_, raw, _ := m.GenerateAPIKey("new", RoleReadOnly, nil)
|
||||
n := countBcrypt(t)
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw+"x"); err == nil {
|
||||
t.Fatal("bad key accepted")
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("%d bcrypt compares with 20 legacy keys stored, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyComparesAreConcurrencyBounded(t *testing.T) {
|
||||
m := newTestManager()
|
||||
for i := 0; i < 5; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
var cur, peak atomic.Int64
|
||||
orig := bcryptCompare
|
||||
bcryptCompare = func(h, p []byte) error {
|
||||
c := cur.Add(1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if c <= p || peak.CompareAndSwap(p, c) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
cur.Add(-1)
|
||||
return orig(h, p)
|
||||
}
|
||||
t.Cleanup(func() { bcryptCompare = orig })
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 40; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = m.ValidateAPIKey(context.Background(), "bad-legacy-key-bad-legacy-key-bad-legacy-key-0000")
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if got := peak.Load(); got > maxLegacyCompares {
|
||||
t.Errorf("peak concurrent legacy compares %d, want <= %d", got, maxLegacyCompares)
|
||||
}
|
||||
}
|
||||
Vendored
+263
-86
@@ -8,11 +8,11 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
hoarderconfig "github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/events"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
@@ -49,10 +49,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 +80,36 @@ 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
|
||||
TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL
|
||||
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)
|
||||
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
|
||||
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
|
||||
|
||||
// maxPurgeBatches bounds the soft-delete purge of one cleanup pass; the next pass continues.
|
||||
const maxPurgeBatches = 100
|
||||
|
||||
// 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,8 +173,12 @@ 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
|
||||
config.DefaultTTL = hoarderconfig.DefaultMetadataTTL
|
||||
}
|
||||
|
||||
if config.CleanupInterval == 0 {
|
||||
@@ -191,6 +213,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 +228,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 +274,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 +330,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 +345,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 +398,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 +584,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.metadataTTL(registry))
|
||||
expiresAt = &exp
|
||||
}
|
||||
|
||||
pkg := &metadata.Package{
|
||||
ID: uuid.New().String(),
|
||||
@@ -570,7 +609,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 +622,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 +639,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.)
|
||||
@@ -662,6 +699,39 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
return pkg, nil
|
||||
}
|
||||
|
||||
// ScanFile returns a local file holding a cached package, for a scan retry. Backends with a
|
||||
// local path serve it directly; others are copied to a temp file that cleanup removes.
|
||||
func (m *Manager) ScanFile(ctx context.Context, registry, name, version string) (string, func(), error) {
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if local, ok := m.storage.(storage.LocalPathProvider); ok {
|
||||
path, pathErr := local.GetLocalPath(ctx, pkg.StorageKey)
|
||||
return path, func() {}, pathErr
|
||||
}
|
||||
rc, err := m.storage.Get(ctx, pkg.StorageKey)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer func() { _ = rc.Close() }()
|
||||
tmp, err := os.CreateTemp(os.TempDir(), "gohoarder-rescan-*")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
cleanup := func() { _ = os.Remove(tmp.Name()) } // #nosec G104 -- cleanup
|
||||
if _, err := io.Copy(tmp, rc); err != nil {
|
||||
_ = tmp.Close() // #nosec G104 -- cleanup
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp.Name(), cleanup, nil
|
||||
}
|
||||
|
||||
// Delete removes a package from cache
|
||||
func (m *Manager) Delete(ctx context.Context, registry, name, version string) error {
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
@@ -672,6 +742,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er
|
||||
return m.deletePackage(ctx, pkg)
|
||||
}
|
||||
|
||||
// metadataTTL returns the freshness window for a registry's metadata entries.
|
||||
func (m *Manager) metadataTTL(registry string) time.Duration {
|
||||
if ttl, ok := m.config.TTLOverrides[registry]; ok {
|
||||
return ttl
|
||||
}
|
||||
return m.config.DefaultTTL
|
||||
}
|
||||
|
||||
// deletePackage deletes a package from both storage and metadata
|
||||
func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error {
|
||||
// Delete from storage
|
||||
@@ -685,19 +763,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 +782,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 +798,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 +807,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 +820,139 @@ 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) })
|
||||
}
|
||||
|
||||
purged := m.purgeDeleted(ctx, start)
|
||||
|
||||
log.Info().
|
||||
Int("expired", expired.count).
|
||||
Int("idle", idle.count).
|
||||
Int64("bytes_freed", expired.bytes+idle.bytes).
|
||||
Dur("idle_ttl", m.config.IdleTTL).
|
||||
Int64("purged_deleted", purged).
|
||||
Dur("deleted_retention", m.config.DeletedRetention).
|
||||
Msg("Cleanup completed")
|
||||
}
|
||||
|
||||
// purgeDeleted hard-deletes soft-deleted rows past DeletedRetention in bounded
|
||||
// batches and returns how many it removed.
|
||||
func (m *Manager) purgeDeleted(ctx context.Context, now time.Time) int64 {
|
||||
if m.config.DeletedRetention <= 0 {
|
||||
return 0
|
||||
}
|
||||
cutoff := now.Add(-m.config.DeletedRetention)
|
||||
var total int64
|
||||
for i := 0; i < maxPurgeBatches && ctx.Err() == nil; i++ {
|
||||
n, err := m.metadata.PurgeDeletedPackages(ctx, cutoff, cleanupBatchSize)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to purge soft-deleted packages")
|
||||
break
|
||||
}
|
||||
total += n
|
||||
if n < cleanupBatchSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// generateStorageKey generates a storage key for a package
|
||||
@@ -853,3 +1022,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
+44
-1
@@ -145,6 +145,30 @@ func (m *MockMetadataStore) ListPackages(ctx context.Context, opts *metadata.Lis
|
||||
return args.Get(0).([]*metadata.Package), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
args := m.Called(ctx, opts)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*metadata.GroupPage), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
args := m.Called(ctx, packageIDs, withDetails)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).([]*metadata.ScanSummary), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
|
||||
args := m.Called(ctx)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).([]metadata.RegistryStat), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) UpdateDownloadCount(ctx context.Context, registry, name, version string) error {
|
||||
args := m.Called(ctx, registry, name, version)
|
||||
return args.Error(0)
|
||||
@@ -230,6 +254,25 @@ 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 }
|
||||
|
||||
func (m *MockMetadataStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, 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.
|
||||
@@ -335,7 +378,7 @@ func TestNew(t *testing.T) {
|
||||
|
||||
// Verify defaults were set
|
||||
if tt.config.DefaultTTL == 0 {
|
||||
assert.Equal(t, 7*24*time.Hour, manager.config.DefaultTTL)
|
||||
assert.Equal(t, 24*time.Hour, manager.config.DefaultTTL)
|
||||
}
|
||||
if tt.config.CleanupInterval == 0 {
|
||||
assert.Equal(t, 1*time.Hour, manager.config.CleanupInterval)
|
||||
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Clients gate on a 72h release age; a metadata page that stays fresh longer would hide the gate's inputs.
|
||||
func TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{})
|
||||
entry := h.get(t, "left-pad", "metadata")
|
||||
|
||||
require.NotNil(t, entry.Package.ExpiresAt)
|
||||
require.Equal(t, 24*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
}
|
||||
|
||||
func TestMetadataEntryExplicitTTLWins(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 6 * time.Hour})
|
||||
entry := h.get(t, "left-pad", "metadata")
|
||||
|
||||
require.Equal(t, 6*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
}
|
||||
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
+90
@@ -0,0 +1,90 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// purgeRecorder plays a store holding `pending` soft-deleted rows.
|
||||
type purgeRecorder struct {
|
||||
*memMetadata
|
||||
err error
|
||||
cutoffs []time.Time
|
||||
limits []int
|
||||
pending int64
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (p *purgeRecorder) PurgeDeletedPackages(_ context.Context, before time.Time, limit int) (int64, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.cutoffs = append(p.cutoffs, before)
|
||||
p.limits = append(p.limits, limit)
|
||||
if p.err != nil {
|
||||
return 0, p.err
|
||||
}
|
||||
n := min(p.pending, int64(limit))
|
||||
p.pending -= n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newPurgeHarness(t *testing.T, retention time.Duration, pending int64) (*idleHarness, *purgeRecorder) {
|
||||
t.Helper()
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
rec := &purgeRecorder{memMetadata: newMemMetadata(h.clock), pending: pending}
|
||||
h.meta = rec.memMetadata
|
||||
mgr, err := New(h.store, rec, nil, nil, Config{Now: h.clock.Now, CleanupInterval: 24 * time.Hour, DeletedRetention: retention})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
h.mgr = mgr
|
||||
return h, rec
|
||||
}
|
||||
|
||||
func TestCleanupPurgesDeletedRowsPastRetention(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 3*int64(cleanupBatchSize)+7)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Zero(t, rec.pending, "batches continue until the store runs dry")
|
||||
require.Len(t, rec.limits, 4, "three full batches and a short one")
|
||||
for _, limit := range rec.limits {
|
||||
require.Equal(t, cleanupBatchSize, limit, "every batch is bounded")
|
||||
}
|
||||
require.Equal(t, h.clock.Now().Add(-30*day), rec.cutoffs[0], "the cutoff is now minus the retention")
|
||||
}
|
||||
|
||||
func TestCleanupPurgeIsBoundedPerPass(t *testing.T) {
|
||||
_, rec := newPurgeHarness(t, 30*day, int64(maxPurgeBatches+50)*int64(cleanupBatchSize))
|
||||
h := &Manager{config: Config{DeletedRetention: day, Now: time.Now}, metadata: rec}
|
||||
|
||||
got := h.purgeDeleted(context.Background(), time.Now())
|
||||
|
||||
require.EqualValues(t, maxPurgeBatches*cleanupBatchSize, got)
|
||||
require.EqualValues(t, 50*cleanupBatchSize, rec.pending, "the next pass continues where this one stopped")
|
||||
}
|
||||
|
||||
func TestCleanupSkipsPurgeWhenRetentionIsZero(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 0, 10)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Empty(t, rec.limits, "zero keeps every row")
|
||||
require.EqualValues(t, 10, rec.pending)
|
||||
}
|
||||
|
||||
func TestCleanupPurgeFailureDoesNotStopCleanup(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 10)
|
||||
rec.err = errors.New("db down")
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.clock.Advance(2 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Len(t, rec.limits, 1, "one failed attempt, no retry loop")
|
||||
require.False(t, h.exists("lodash", "metadata"), "expired metadata is still removed")
|
||||
}
|
||||
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
+75
@@ -0,0 +1,75 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// listingMetadata adds the full listing the rescan worker walks.
|
||||
type listingMetadata struct{ scanMetadata }
|
||||
|
||||
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
|
||||
}
|
||||
|
||||
// bodyScanner reports the bytes it can read at the path it is given.
|
||||
type bodyScanner struct{ seen chan string }
|
||||
|
||||
func (*bodyScanner) Name() string { return "body-scanner" }
|
||||
func (*bodyScanner) Health(context.Context) error { return nil }
|
||||
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
return nil, err
|
||||
}
|
||||
s.seen <- string(body)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
|
||||
// through the cache's file source instead of skipping the package.
|
||||
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
bs := &bodyScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(bs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
|
||||
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
CachedAt: clock.Now(), LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { worker.Start(runCtx); close(done) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
|
||||
select {
|
||||
case got := <-bs.seen:
|
||||
require.Equal(t, "tarball-bytes", got)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("rescan never scanned the remote-storage package")
|
||||
}
|
||||
}
|
||||
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// scanMetadata lets the real scanner.Manager record results against the in-memory store.
|
||||
type scanMetadata struct {
|
||||
*memMetadata
|
||||
}
|
||||
|
||||
func (scanMetadata) SaveScanResult(context.Context, *metadata.ScanResult) error { return nil }
|
||||
func (scanMetadata) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
|
||||
return nil, fmt.Errorf("no result")
|
||||
}
|
||||
|
||||
// fileScanner fails on infrastructure once, then succeeds; it records what it could read.
|
||||
type fileScanner struct {
|
||||
seen chan string
|
||||
mu sync.Mutex
|
||||
n int
|
||||
}
|
||||
|
||||
func (*fileScanner) Name() string { return "file-scanner" }
|
||||
func (*fileScanner) Health(context.Context) error { return nil }
|
||||
func (s *fileScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
s.mu.Lock()
|
||||
s.n++
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
} else {
|
||||
s.seen <- string(body)
|
||||
}
|
||||
if n == 1 {
|
||||
return nil, fmt.Errorf("%w: scanner timed out", scanerr.ErrInfrastructure)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "file-scanner", Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// On a backend with no local path (S3, SMB) the scan source is a temp file removed after the
|
||||
// first scan; a retry must read the blob again instead of scanning a path that is gone.
|
||||
func TestScanRetryOnRemoteStorageReadsBlobAgain(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := scanMetadata{newMemMetadata(clock)}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 50 * time.Millisecond}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
fs := &fileScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(fs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour, ScanWaitTimeout: 200 * time.Millisecond})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("tarball-bytes"))}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, entry.Data)
|
||||
_ = entry.Data.Close()
|
||||
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
select {
|
||||
case got := <-fs.seen:
|
||||
require.Equal(t, "tarball-bytes", got, "scan attempt %d must read the blob", attempt)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("scan attempt %d never ran", attempt)
|
||||
}
|
||||
}
|
||||
}
|
||||
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")
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry {
|
||||
t.Helper()
|
||||
entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{
|
||||
DefaultTTL: 6 * time.Hour,
|
||||
TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour},
|
||||
})
|
||||
|
||||
require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl")
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}})
|
||||
|
||||
require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry")
|
||||
}
|
||||
+61
-16
@@ -35,6 +35,7 @@ type ServerConfig struct {
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout"`
|
||||
IdleTimeout time.Duration `mapstructure:"idle_timeout" json:"idle_timeout"`
|
||||
ReadBufferSize int `mapstructure:"read_buffer_size" json:"read_buffer_size"` // bytes; caps the request line plus headers
|
||||
}
|
||||
|
||||
// TLSConfig contains TLS/HTTPS configuration
|
||||
@@ -133,13 +134,42 @@ type MySQLConfig struct {
|
||||
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
|
||||
}
|
||||
|
||||
// DefaultMetadataTTL is the freshness window for metadata pages. It stays below the 72h
|
||||
// release-age gate clients apply, so a cached page never hides the entries the gate reads.
|
||||
const DefaultMetadataTTL = 24 * time.Hour
|
||||
|
||||
// DefaultReadBufferSize is the HTTP server read buffer. Fiber's own 8192 rejects browsers
|
||||
// that send OIDC session cookies plus a long Referer or URL with 431.
|
||||
const DefaultReadBufferSize = 16384
|
||||
|
||||
// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name.
|
||||
var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"}
|
||||
|
||||
// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name.
|
||||
func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
|
||||
out := make(map[string]time.Duration, len(c.TTLOverrides))
|
||||
for key, ttl := range c.TTLOverrides {
|
||||
out[ttlOverrideRegistries[key]] = ttl
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
// DefaultDeletedRetention is how long a soft-deleted package row is kept before cleanup purges it.
|
||||
const DefaultDeletedRetention = 30 * 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"`
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
|
||||
// DeletedRetention is how long soft-deleted package rows stay before cleanup purges them; 0 keeps them forever.
|
||||
DeletedRetention time.Duration `mapstructure:"deleted_retention" json:"deleted_retention"`
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
}
|
||||
|
||||
// SecurityConfig contains security scanning configuration
|
||||
@@ -326,11 +356,12 @@ type PyPIHandlerConfig struct {
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
ReadBufferSize: DefaultReadBufferSize,
|
||||
TLS: TLSConfig{
|
||||
Enabled: false,
|
||||
},
|
||||
@@ -351,15 +382,12 @@ func Default() *Config {
|
||||
},
|
||||
},
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: 7 * 24 * time.Hour,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
"npm": 7 * 24 * time.Hour,
|
||||
"pip": 7 * 24 * time.Hour,
|
||||
"go": 7 * 24 * time.Hour,
|
||||
},
|
||||
DefaultTTL: DefaultMetadataTTL,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
DeletedRetention: DefaultDeletedRetention,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
},
|
||||
Security: SecurityConfig{
|
||||
Enabled: false,
|
||||
@@ -502,9 +530,26 @@ func (c *Config) Validate() error {
|
||||
}
|
||||
|
||||
// Validate cache
|
||||
if c.Server.ReadBufferSize < 0 {
|
||||
return fmt.Errorf("server.read_buffer_size cannot be negative")
|
||||
}
|
||||
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")
|
||||
}
|
||||
for key, ttl := range c.Cache.TTLOverrides {
|
||||
if _, ok := ttlOverrideRegistries[key]; !ok {
|
||||
return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key)
|
||||
}
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
|
||||
}
|
||||
}
|
||||
if c.Cache.DeletedRetention < 0 {
|
||||
return fmt.Errorf("cache.deleted_retention cannot be negative")
|
||||
}
|
||||
if c.Cache.MaxSizeBytes < 0 {
|
||||
return fmt.Errorf("cache.max_size_bytes cannot be negative")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDefaultMetadataTTL(t *testing.T) {
|
||||
require.Equal(t, 24*time.Hour, Default().Cache.DefaultTTL)
|
||||
for registry, ttl := range Default().Cache.TTLOverrides {
|
||||
require.LessOrEqual(t, ttl, 72*time.Hour, "override %s outlives the 72h release-age gate", registry)
|
||||
}
|
||||
}
|
||||
|
||||
// The shipped examples must not teach a metadata TTL longer than the release-age gate.
|
||||
func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) {
|
||||
for file, key := range map[string]string{
|
||||
"../../config.yaml.example": `default_ttl`,
|
||||
"../../helm/gohoarder/values.yaml": `defaultTTL`,
|
||||
} {
|
||||
raw, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
m := regexp.MustCompile(`(?m)^\s*` + key + `:\s*"?(\d+h)"?`).FindSubmatch(raw)
|
||||
require.NotNil(t, m, "%s has no %s", file, key)
|
||||
ttl, err := time.ParseDuration(string(m[1]))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 24*time.Hour, ttl, file)
|
||||
|
||||
for _, o := range regexp.MustCompile(`(?m)^\s+(?:npm|pip|go):\s*"(\d+h)"`).FindAllSubmatch(raw, -1) {
|
||||
d, err := time.ParseDuration(string(o[1]))
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, d, 72*time.Hour, "%s: override %s", file, o[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTLOverridesValidation(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
overrides map[string]time.Duration
|
||||
wantErr string
|
||||
}{
|
||||
"known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""},
|
||||
"pip alias": {map[string]time.Duration{"pip": time.Hour}, ""},
|
||||
"unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"},
|
||||
"zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"},
|
||||
"negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := Default()
|
||||
c.Cache.TTLOverrides = tc.overrides
|
||||
err := c.Validate()
|
||||
if tc.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.ErrorContains(t, err, tc.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesNormalisesPip(t *testing.T) {
|
||||
c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}}
|
||||
require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides())
|
||||
}
|
||||
|
||||
func TestDefaultsKeepNoTTLOverrides(t *testing.T) {
|
||||
require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl")
|
||||
}
|
||||
|
||||
func TestLoadReadsTTLOverridesFromYAML(t *testing.T) {
|
||||
write := func(body string) string {
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
|
||||
return path
|
||||
}
|
||||
|
||||
cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides())
|
||||
|
||||
_, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n"))
|
||||
require.ErrorContains(t, err, "cache.ttl_overrides")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDeletedRetentionDefaultsToThirtyDays(t *testing.T) {
|
||||
require.Equal(t, 30*24*time.Hour, Default().Cache.DeletedRetention)
|
||||
|
||||
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 30*24*time.Hour, cfg.Cache.DeletedRetention, "an unset key keeps the default")
|
||||
}
|
||||
|
||||
func TestDeletedRetentionParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want time.Duration
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "duration string", yaml: "cache:\n deleted_retention: 48h\n", want: 48 * time.Hour},
|
||||
{name: "zero keeps rows", yaml: "cache:\n deleted_retention: 0\n", want: 0},
|
||||
{name: "quoted duration", yaml: "cache:\n deleted_retention: \"720h\"\n", want: 720 * time.Hour},
|
||||
{name: "negative rejected", yaml: "cache:\n deleted_retention: -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.deleted_retention")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, cfg.Cache.DeletedRetention)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// packageKey identifies a file-store record, which has no numeric id.
|
||||
func packageKey(p *metadata.Package) string {
|
||||
return p.Registry + "/" + p.Name + "@" + p.Version
|
||||
}
|
||||
|
||||
// listRecords returns package records only: the store's walk also yields scan result files.
|
||||
func (s *Store) listRecords(ctx context.Context) ([]*metadata.Package, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := all[:0]
|
||||
for _, p := range all {
|
||||
if p.Registry != "" && p.Name != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListPackageGroups pages groups in memory.
|
||||
func (s *Store) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, p := range all {
|
||||
if p.ID == "" {
|
||||
p.ID = packageKey(p)
|
||||
}
|
||||
}
|
||||
if len(opts.Severities) > 0 {
|
||||
if all, err = s.withSeverity(ctx, all, opts.Severities); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return metadata.PageGroups(all, opts), nil
|
||||
}
|
||||
|
||||
// withSeverity keeps the packages whose scan holds a vulnerability of one of the severities.
|
||||
func (s *Store) withSeverity(ctx context.Context, all []*metadata.Package, severities []string) ([]*metadata.Package, error) {
|
||||
sums, err := s.GetScanSummaries(ctx, nil, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hit := make(map[string]struct{}, len(sums))
|
||||
for _, sum := range sums {
|
||||
for _, sev := range severities {
|
||||
if (sev == metadata.SeverityCritical && sum.Critical > 0) || (sev == metadata.SeverityHigh && sum.High > 0) ||
|
||||
(sev == metadata.SeverityModerate && sum.Moderate > 0) || (sev == metadata.SeverityLow && sum.Low > 0) {
|
||||
hit[sum.PackageID] = struct{}{}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
out := all[:0]
|
||||
for _, p := range all {
|
||||
if _, ok := hit[p.ID]; ok {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetScanSummaries reads each scanned package's latest scan file.
|
||||
func (s *Store) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
want := make(map[string]struct{}, len(packageIDs))
|
||||
for _, id := range packageIDs {
|
||||
want[id] = struct{}{}
|
||||
}
|
||||
var out []*metadata.ScanSummary
|
||||
for _, p := range all {
|
||||
id := p.ID
|
||||
if id == "" {
|
||||
id = packageKey(p)
|
||||
}
|
||||
if _, ok := want[id]; packageIDs != nil && !ok || !p.SecurityScanned {
|
||||
continue
|
||||
}
|
||||
sum := &metadata.ScanSummary{
|
||||
Registry: p.Registry, PackageID: id, Name: p.Name, Version: p.Version, ReleaseVersion: p.ReleaseVersion,
|
||||
}
|
||||
res, err := s.GetScanResult(ctx, p.Registry, p.Name, p.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res != nil {
|
||||
sum.HasScan = true
|
||||
sum.Status = res.Status
|
||||
sum.ScannedAt = res.ScannedAt
|
||||
sum.Total = res.VulnerabilityCount
|
||||
sum.Details = res.Details
|
||||
for _, v := range res.Vulnerabilities {
|
||||
switch metadata.NormalizeSeverity(v.Severity) {
|
||||
case "CRITICAL":
|
||||
sum.Critical++
|
||||
case "HIGH":
|
||||
sum.High++
|
||||
case "MODERATE":
|
||||
sum.Moderate++
|
||||
default:
|
||||
sum.Low++
|
||||
}
|
||||
}
|
||||
if withDetails {
|
||||
sum.Vulnerabilities = res.Vulnerabilities
|
||||
}
|
||||
}
|
||||
out = append(out, sum)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetRegistryStats totals artifacts per registry.
|
||||
func (s *Store) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byRegistry := map[string]*metadata.RegistryStat{}
|
||||
var order []string
|
||||
for _, p := range all {
|
||||
if metadata.IsMetadataVersion(p.Version) {
|
||||
continue
|
||||
}
|
||||
st, ok := byRegistry[p.Registry]
|
||||
if !ok {
|
||||
st = &metadata.RegistryStat{Registry: p.Registry}
|
||||
byRegistry[p.Registry] = st
|
||||
order = append(order, p.Registry)
|
||||
}
|
||||
st.Count++
|
||||
st.Size += p.Size
|
||||
st.Downloads += p.DownloadCount
|
||||
}
|
||||
out := make([]metadata.RegistryStat, 0, len(order))
|
||||
for _, r := range order {
|
||||
out = append(out, *byRegistry[r])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -146,9 +147,9 @@ func (s *Store) ListPackages(ctx context.Context, opts *metadata.ListOptions) ([
|
||||
return []*metadata.Package{}, nil
|
||||
}
|
||||
|
||||
end := opts.Offset + opts.Limit
|
||||
if end > len(packages) {
|
||||
end = len(packages)
|
||||
end := len(packages)
|
||||
if opts.Limit > 0 && opts.Offset+opts.Limit < end {
|
||||
end = opts.Offset + opts.Limit
|
||||
}
|
||||
|
||||
return packages[opts.Offset:end], nil
|
||||
@@ -157,6 +158,73 @@ 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 })
|
||||
}
|
||||
|
||||
// PurgeDeletedPackages is a no-op: the file store deletes packages outright.
|
||||
func (s *Store) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// GetStatsTrend returns no history: the file store keeps no daily snapshots.
|
||||
func (s *Store) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
@@ -82,3 +82,57 @@ func TestCleanupExpiredBypasses_DoesNotFollowSymlinkOutsideStore(t *testing.T) {
|
||||
require.Error(t, err, "escaping symlink must be refused, not read")
|
||||
require.FileExists(t, target)
|
||||
}
|
||||
|
||||
func TestListPackagesZeroLimitMeansNoLimit(t *testing.T) {
|
||||
store, err := New(Config{Path: t.TempDir()})
|
||||
require.NoError(t, err)
|
||||
ctx := context.Background()
|
||||
for _, v := range []string{"1", "2", "3"} {
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{Registry: "npm", Name: "p", Version: v}))
|
||||
}
|
||||
got, err := store.ListPackages(ctx, &metadata.ListOptions{Offset: 1})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
}
|
||||
|
||||
func TestFileStoreDashboardQueries(t *testing.T) {
|
||||
store, err := New(Config{Path: t.TempDir()})
|
||||
require.NoError(t, err)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for _, p := range []*metadata.Package{
|
||||
{Registry: "npm", Name: "a", Version: "1", Size: 10, DownloadCount: 2, SecurityScanned: true, CachedAt: now},
|
||||
{Registry: "npm", Name: "a", Version: "list", Size: 1, CachedAt: now},
|
||||
{Registry: "go", Name: "m", Version: "v1", Size: 30, DownloadCount: 1, CachedAt: now},
|
||||
} {
|
||||
require.NoError(t, store.SavePackage(ctx, p))
|
||||
}
|
||||
require.NoError(t, store.SaveScanResult(ctx, &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: "a", PackageVersion: "1", Scanner: "t", Status: metadata.ScanStatusVulnerable, ScannedAt: now,
|
||||
VulnerabilityCount: 1, Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: "high"}},
|
||||
}))
|
||||
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Page: 1, PageSize: 10})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, page.TotalGroups)
|
||||
require.Len(t, page.Packages, 2)
|
||||
|
||||
sums, err := store.GetScanSummaries(ctx, nil, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, sums, 1)
|
||||
require.True(t, sums[0].HasScan)
|
||||
require.Equal(t, 1, sums[0].High)
|
||||
require.Len(t, sums[0].Vulnerabilities, 1)
|
||||
|
||||
byID, err := store.GetScanSummaries(ctx, []string{sums[0].PackageID}, false)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, byID, 1)
|
||||
require.Nil(t, byID[0].Vulnerabilities)
|
||||
|
||||
stats, err := store.GetRegistryStats(ctx)
|
||||
require.NoError(t, err)
|
||||
require.ElementsMatch(t, []metadata.RegistryStat{
|
||||
{Registry: "npm", Count: 1, Size: 10, Downloads: 2},
|
||||
{Registry: "go", Count: 1, Size: 30, Downloads: 1},
|
||||
}, stats)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -1,17 +1,28 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"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
|
||||
blocked func(context.Context) (int64, error)
|
||||
wg sync.WaitGroup
|
||||
stopOnce sync.Once
|
||||
mu sync.Mutex // guards blocked
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -23,6 +34,23 @@ 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()
|
||||
}
|
||||
|
||||
// StartAsync runs Start in a goroutine that Stop waits for.
|
||||
func (w *AggregationWorker) StartAsync() {
|
||||
w.wg.Add(1)
|
||||
go func() {
|
||||
defer w.wg.Done()
|
||||
w.Start()
|
||||
}()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -55,9 +83,10 @@ func (w *AggregationWorker) Start() {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop stops the aggregation worker
|
||||
// Stop stops the aggregation worker and waits for a started one to exit. Safe to call repeatedly.
|
||||
func (w *AggregationWorker) Stop() {
|
||||
close(w.stopChan)
|
||||
w.stopOnce.Do(func() { close(w.stopChan) })
|
||||
w.wg.Wait()
|
||||
}
|
||||
|
||||
// AggregateHourly aggregates download events into hourly stats
|
||||
@@ -69,7 +98,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
|
||||
@@ -126,7 +155,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
// SQLite: Use strftime for time bucketing
|
||||
// Note: SQLite doesn't support UPSERT as elegantly, need to handle separately
|
||||
aggregateSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
SELECT
|
||||
de.registry_id,
|
||||
de.package_id,
|
||||
@@ -139,6 +168,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
FROM download_events de
|
||||
WHERE de.downloaded_at < ?
|
||||
GROUP BY de.registry_id, de.package_id, time_bucket
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = download_stats_hourly.download_count + excluded.download_count,
|
||||
unique_ips = MAX(download_stats_hourly.unique_ips, excluded.unique_ips),
|
||||
auth_downloads = download_stats_hourly.auth_downloads + excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -208,7 +243,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
default:
|
||||
// SQLite
|
||||
registryAggSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
SELECT
|
||||
registry_id,
|
||||
NULL as package_id,
|
||||
@@ -221,6 +256,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
FROM download_stats_hourly
|
||||
WHERE package_id IS NOT NULL
|
||||
GROUP BY registry_id, time_bucket
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = excluded.download_count,
|
||||
unique_ips = excluded.unique_ips,
|
||||
auth_downloads = excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -245,11 +286,13 @@ 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 {
|
||||
err := w.db.Transaction(func(tx *gorm.DB) error {
|
||||
var aggregateSQL string
|
||||
|
||||
switch dialectName {
|
||||
@@ -302,7 +345,7 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
default: // SQLite
|
||||
aggregateSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||
INSERT INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||
SELECT
|
||||
registry_id,
|
||||
package_id,
|
||||
@@ -316,15 +359,21 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
FROM download_stats_hourly
|
||||
WHERE time_bucket >= ? AND time_bucket < ?
|
||||
GROUP BY registry_id, package_id, date(time_bucket)
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = excluded.download_count,
|
||||
unique_ips = excluded.unique_ips,
|
||||
auth_downloads = excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
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
|
||||
@@ -338,6 +387,15 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The snapshot is not part of the rollup: a failure here must not undo it.
|
||||
if err := w.SnapshotStats(context.Background()); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to record stats snapshot")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdatePackageAccessCounts synchronizes package access_count from download stats
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package gormstore
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloseIsIdempotent(t *testing.T) {
|
||||
store := openFileStore(t, true)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("first Close: %v", err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("second Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// likeEscape is the ESCAPE character for search patterns; unlike a backslash it
|
||||
// means the same thing on SQLite, PostgreSQL and MySQL.
|
||||
const likeEscape = "!"
|
||||
|
||||
// scanErrorStatus marks a failed scan whose details decide whether it blocks.
|
||||
const scanErrorStatus = string(metadata.ScanStatusError)
|
||||
|
||||
// baseNameExpr is the SQL that strips the Go "/@v/<file>" suffix from a package name.
|
||||
func (s *GORMStoreV2) baseNameExpr() string {
|
||||
switch s.db.Name() {
|
||||
case "postgres":
|
||||
return "split_part(name, '/@v/', 1)"
|
||||
case "mysql":
|
||||
return "SUBSTRING_INDEX(name, '/@v/', 1)"
|
||||
default:
|
||||
return "CASE WHEN instr(name, '/@v/') > 0 THEN substr(name, 1, instr(name, '/@v/') - 1) ELSE name END"
|
||||
}
|
||||
}
|
||||
|
||||
func escapeLike(q string) string {
|
||||
r := strings.NewReplacer(likeEscape, likeEscape+likeEscape, "%", likeEscape+"%", "_", likeEscape+"_")
|
||||
return "%" + r.Replace(strings.ToLower(q)) + "%"
|
||||
}
|
||||
|
||||
// registryNames snapshots the id to name mapping.
|
||||
func (s *GORMStoreV2) registryNames() map[int32]string {
|
||||
s.registryCacheMu.RLock()
|
||||
defer s.registryCacheMu.RUnlock()
|
||||
names := make(map[int32]string, len(s.registryCache))
|
||||
for name, id := range s.registryCache {
|
||||
names[id] = name
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// groupFilter builds the WHERE clause shared by the group count, the group page and the row fetch.
|
||||
func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string, args []interface{}, empty bool, err error) {
|
||||
clause = "version NOT IN ?"
|
||||
args = []interface{}{metadata.MetadataVersions}
|
||||
if opts.Registry != "" {
|
||||
id, idErr := s.getRegistryID(opts.Registry)
|
||||
if idErr != nil {
|
||||
var hErr *errors.Error
|
||||
if stderrors.As(idErr, &hErr) && hErr.Code == errors.ErrCodeNotFound {
|
||||
return "", nil, true, nil
|
||||
}
|
||||
return "", nil, false, idErr
|
||||
}
|
||||
clause += " AND registry_id = ?"
|
||||
args = append(args, id)
|
||||
}
|
||||
if sev := severityFilter(opts.Severities); sev != "" {
|
||||
clause += " AND security_scanned = ? AND id IN (" + latestScanWith(sev) + ")"
|
||||
args = append(args, true)
|
||||
}
|
||||
if q := strings.TrimSpace(opts.Query); q != "" {
|
||||
like := escapeLike(q)
|
||||
clause += " AND (LOWER(name) LIKE ? ESCAPE '" + likeEscape + "'" +
|
||||
" OR LOWER(version) LIKE ? ESCAPE '" + likeEscape + "'" +
|
||||
" OR LOWER(release_version) LIKE ? ESCAPE '" + likeEscape + "')"
|
||||
args = append(args, like, like, like)
|
||||
}
|
||||
return clause, args, false, nil
|
||||
}
|
||||
|
||||
// severityColumns maps a severity filter value to its scan_results count column.
|
||||
var severityColumns = map[string]string{
|
||||
metadata.SeverityCritical: "critical_count",
|
||||
metadata.SeverityHigh: "high_count",
|
||||
metadata.SeverityModerate: "medium_count",
|
||||
metadata.SeverityLow: "low_count",
|
||||
}
|
||||
|
||||
// severityFilter ORs the count columns of the known severities; unknown values are ignored.
|
||||
func severityFilter(severities []string) string {
|
||||
var conds []string
|
||||
seen := map[string]bool{}
|
||||
for _, sev := range severities {
|
||||
col, ok := severityColumns[sev]
|
||||
if !ok || seen[sev] {
|
||||
continue
|
||||
}
|
||||
seen[sev] = true
|
||||
conds = append(conds, col+" > 0")
|
||||
}
|
||||
return strings.Join(conds, " OR ")
|
||||
}
|
||||
|
||||
// latestScanWith selects the packages whose newest scan satisfies cond. A tie on
|
||||
// scanned_at goes to the higher id, as GetScanSummaries decides it.
|
||||
func latestScanWith(cond string) string {
|
||||
return `SELECT package_id FROM scan_results WHERE deleted_at IS NULL AND (` + cond + `)
|
||||
AND scanned_at = (SELECT MAX(x.scanned_at) FROM scan_results x WHERE x.package_id = scan_results.package_id AND x.deleted_at IS NULL)
|
||||
AND NOT EXISTS (SELECT 1 FROM scan_results y WHERE y.package_id = scan_results.package_id AND y.deleted_at IS NULL
|
||||
AND y.scanned_at = scan_results.scanned_at AND y.id > scan_results.id)`
|
||||
}
|
||||
|
||||
// groupOrder is the ORDER BY of the group page query.
|
||||
// It reads the aliases of the grouped subquery, which MySQL's only_full_group_by requires.
|
||||
func groupOrder(opts metadata.GroupListOptions) string {
|
||||
dir := "ASC"
|
||||
if opts.SortDesc {
|
||||
dir = "DESC"
|
||||
}
|
||||
var lead string
|
||||
switch opts.SortBy {
|
||||
case metadata.GroupSortCachedAt:
|
||||
lead = "last_cached " + dir + ", "
|
||||
case metadata.GroupSortDownloads:
|
||||
lead = "downloads " + dir + ", "
|
||||
case metadata.GroupSortSize:
|
||||
lead = "total_size " + dir + ", "
|
||||
}
|
||||
nameDir := "ASC"
|
||||
if lead == "" && opts.SortDesc {
|
||||
nameDir = "DESC"
|
||||
}
|
||||
return lead + "LOWER(base_name) " + nameDir + ", base_name " + nameDir + ", registry_id ASC"
|
||||
}
|
||||
|
||||
type groupKey struct {
|
||||
name string
|
||||
registryID int32
|
||||
}
|
||||
|
||||
// ListPackageGroups returns one page of groups with all their version rows in four statements at most.
|
||||
func (s *GORMStoreV2) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
page := &metadata.GroupPage{}
|
||||
clause, args, empty, err := s.groupFilter(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if empty {
|
||||
return page, nil
|
||||
}
|
||||
base := s.baseNameExpr()
|
||||
matching := func() *gorm.DB {
|
||||
return s.db.WithContext(ctx).Model(&PackageModel{}).Where(clause, args...)
|
||||
}
|
||||
|
||||
var rows []PackageModel
|
||||
if opts.PageSize <= 0 {
|
||||
// Everything is wanted, so order the groups in memory with the reference implementation.
|
||||
if err := matching().Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
|
||||
}
|
||||
opts.Registry, opts.Query = "", ""
|
||||
return metadata.PageGroups(s.modelsToPackages(rows), opts), nil
|
||||
}
|
||||
|
||||
distinct := matching().
|
||||
Select("registry_id, " + base + " AS base_name, MAX(cached_at) AS last_cached, SUM(access_count) AS downloads, SUM(size) AS total_size").
|
||||
Group("registry_id, " + base)
|
||||
if err := s.db.WithContext(ctx).Table("(?) AS g", distinct).Select("COUNT(*)").Scan(&page.TotalGroups).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to count package groups")
|
||||
}
|
||||
if page.TotalGroups == 0 {
|
||||
return page, nil
|
||||
}
|
||||
|
||||
pageNo := opts.Page
|
||||
if pageNo < 1 {
|
||||
pageNo = 1
|
||||
}
|
||||
var keys []struct {
|
||||
BaseName string
|
||||
RegistryID int32
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Table("(?) AS g", distinct).Select("registry_id, base_name").
|
||||
Order(groupOrder(opts)).
|
||||
Limit(opts.PageSize).Offset((pageNo - 1) * opts.PageSize).
|
||||
Scan(&keys).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to page package groups")
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return page, nil
|
||||
}
|
||||
order := make([]groupKey, len(keys))
|
||||
registryIDs := make([]int32, 0, len(keys))
|
||||
names := make([]string, 0, len(keys))
|
||||
for i, k := range keys {
|
||||
order[i] = groupKey{name: k.BaseName, registryID: k.RegistryID}
|
||||
registryIDs = append(registryIDs, k.RegistryID)
|
||||
names = append(names, k.BaseName)
|
||||
}
|
||||
|
||||
if err := matching().
|
||||
Where("registry_id IN ? AND "+base+" IN ?", registryIDs, names).
|
||||
Order("cached_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list group packages")
|
||||
}
|
||||
return s.orderGroupRows(page, rows, order), nil
|
||||
}
|
||||
|
||||
// orderGroupRows converts rows, dedupes Go file variants and sorts them into the page's group order.
|
||||
func (s *GORMStoreV2) orderGroupRows(page *metadata.GroupPage, rows []PackageModel, order []groupKey) *metadata.GroupPage {
|
||||
names := s.registryNames()
|
||||
rank := make(map[string]int, len(order))
|
||||
for i, k := range order {
|
||||
rank[names[k.registryID]+"\x00"+k.name] = i
|
||||
}
|
||||
var kept []*metadata.Package
|
||||
for _, p := range metadata.DedupeVersions(s.modelsToPackages(rows)) {
|
||||
if _, ok := rank[p.Registry+"\x00"+p.Name]; ok {
|
||||
kept = append(kept, p)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(kept, func(i, j int) bool {
|
||||
return rank[kept[i].Registry+"\x00"+kept[i].Name] < rank[kept[j].Registry+"\x00"+kept[j].Name]
|
||||
})
|
||||
page.Packages = kept
|
||||
return page
|
||||
}
|
||||
|
||||
// GetScanSummaries returns the latest scan per package in two statements (three when a scan failed and details are lazily loaded).
|
||||
func (s *GORMStoreV2) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
var ids []int64
|
||||
for _, raw := range packageIDs {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if packageIDs != nil && len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pkgQuery := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Select("id, registry_id, name, version, release_version").
|
||||
Where("security_scanned = ?", true)
|
||||
if packageIDs != nil {
|
||||
pkgQuery = pkgQuery.Where("id IN ?", ids)
|
||||
}
|
||||
var pkgs []PackageModel
|
||||
if err := pkgQuery.Order("id").Find(&pkgs).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to load scanned packages")
|
||||
}
|
||||
if len(pkgs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
columns := "id, package_id, status, scanned_at, vuln_count, critical_count, high_count, medium_count, low_count"
|
||||
if withDetails {
|
||||
columns += ", details"
|
||||
}
|
||||
scanQuery := s.db.WithContext(ctx).Model(&ScanResultModel{}).Select(columns).
|
||||
Where("scanned_at = (SELECT MAX(x.scanned_at) FROM scan_results x WHERE x.package_id = scan_results.package_id AND x.deleted_at IS NULL)")
|
||||
if packageIDs != nil {
|
||||
scanQuery = scanQuery.Where("package_id IN ?", ids)
|
||||
} else {
|
||||
scanQuery = scanQuery.Where("package_id IN (SELECT id FROM packages WHERE security_scanned = ? AND deleted_at IS NULL)", true)
|
||||
}
|
||||
var scans []ScanResultModel
|
||||
if err := scanQuery.Find(&scans).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to load scan results")
|
||||
}
|
||||
latest := make(map[int64]*ScanResultModel, len(scans))
|
||||
for i := range scans {
|
||||
// Equal timestamps return two rows; the newer insert wins.
|
||||
if cur, ok := latest[scans[i].PackageID]; !ok || scans[i].ID > cur.ID {
|
||||
latest[scans[i].PackageID] = &scans[i]
|
||||
}
|
||||
}
|
||||
|
||||
if !withDetails {
|
||||
if err := s.loadFailedScanDetails(ctx, latest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
names := s.registryNames()
|
||||
out := make([]*metadata.ScanSummary, 0, len(pkgs))
|
||||
for i := range pkgs {
|
||||
p := &pkgs[i]
|
||||
sum := &metadata.ScanSummary{
|
||||
Registry: names[p.RegistryID],
|
||||
PackageID: strconv.FormatInt(p.ID, 10),
|
||||
Name: p.Name,
|
||||
Version: p.Version,
|
||||
ReleaseVersion: p.ReleaseVersion,
|
||||
}
|
||||
if scan, ok := latest[p.ID]; ok {
|
||||
sum.HasScan = true
|
||||
sum.Status = metadata.ScanStatus(scan.Status)
|
||||
sum.ScannedAt = scan.ScannedAt
|
||||
sum.Total = scan.VulnCount
|
||||
sum.Critical = scan.CriticalCount
|
||||
sum.High = scan.HighCount
|
||||
sum.Moderate = scan.MediumCount
|
||||
sum.Low = scan.LowCount
|
||||
if withDetails {
|
||||
sum.Vulnerabilities = vulnerabilitiesFromDetails(scan.Details)
|
||||
}
|
||||
if scan.Status == scanErrorStatus || withDetails {
|
||||
sum.Details = map[string]interface{}(scan.Details)
|
||||
}
|
||||
}
|
||||
out = append(out, sum)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// loadFailedScanDetails fills Details for failed scans, which carry the infrastructure-error flag.
|
||||
func (s *GORMStoreV2) loadFailedScanDetails(ctx context.Context, latest map[int64]*ScanResultModel) error {
|
||||
var failed []int64
|
||||
for _, scan := range latest {
|
||||
if scan.Status == scanErrorStatus {
|
||||
failed = append(failed, scan.ID)
|
||||
}
|
||||
}
|
||||
if len(failed) == 0 {
|
||||
return nil
|
||||
}
|
||||
var rows []ScanResultModel
|
||||
if err := s.db.WithContext(ctx).Model(&ScanResultModel{}).
|
||||
Select("id, details").Where("id IN ?", failed).Find(&rows).Error; err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to load failed scan details")
|
||||
}
|
||||
details := make(map[int64]JSONBField, len(rows))
|
||||
for _, r := range rows {
|
||||
details[r.ID] = r.Details
|
||||
}
|
||||
for _, scan := range latest {
|
||||
if scan.Status == scanErrorStatus {
|
||||
scan.Details = details[scan.ID]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRegistryStats groups cache artifacts by registry in one statement.
|
||||
func (s *GORMStoreV2) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
|
||||
var rows []struct {
|
||||
RegistryID int32
|
||||
Count int64
|
||||
Size int64
|
||||
Downloads int64
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Select("registry_id, COUNT(*) AS count, COALESCE(SUM(size), 0) AS size, COALESCE(SUM(access_count), 0) AS downloads").
|
||||
Where("version NOT IN ?", metadata.MetadataVersions).
|
||||
Group("registry_id").Order("registry_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to aggregate registry stats")
|
||||
}
|
||||
names := s.registryNames()
|
||||
out := make([]metadata.RegistryStat, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, metadata.RegistryStat{Registry: names[r.RegistryID], Count: r.Count, Size: r.Size, Downloads: r.Downloads})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilitiesFromDetails decodes the vulnerability list stored in a scan's details.
|
||||
func vulnerabilitiesFromDetails(details JSONBField) []metadata.Vulnerability {
|
||||
var vulnerabilities []metadata.Vulnerability
|
||||
vulnArray, ok := details["vulnerabilities"].([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, v := range vulnArray {
|
||||
vulnMap, ok := v.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
vuln := metadata.Vulnerability{
|
||||
ID: getStringFromMap(vulnMap, "id"),
|
||||
Severity: getStringFromMap(vulnMap, "severity"),
|
||||
Title: getStringFromMap(vulnMap, "title"),
|
||||
Description: getStringFromMap(vulnMap, "description"),
|
||||
FixedIn: getStringFromMap(vulnMap, "fixed_in"),
|
||||
}
|
||||
if refs, ok := vulnMap["references"].([]interface{}); ok {
|
||||
for _, ref := range refs {
|
||||
if refStr, ok := ref.(string); ok {
|
||||
vuln.References = append(vuln.References, refStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if detectedBy, ok := vulnMap["detected_by"].([]interface{}); ok {
|
||||
for _, d := range detectedBy {
|
||||
if dStr, ok := d.(string); ok {
|
||||
vuln.DetectedBy = append(vuln.DetectedBy, dStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
vulnerabilities = append(vulnerabilities, vuln)
|
||||
}
|
||||
return vulnerabilities
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestPostgresDashboardQueries(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages RESTART IDENTITY CASCADE").Error)
|
||||
}
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"groups match the reference": checkListPackageGroupsMatchesReference,
|
||||
"group behaviour": checkListPackageGroupsBehaviour,
|
||||
"statement count is constant": checkDashboardStatementsAreConstant,
|
||||
"scan summaries": checkScanSummaries,
|
||||
"registry stats": checkRegistryStats,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
reset(t)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// With sequential scans disabled the latest-scan lookup must run on the new index.
|
||||
func TestPostgresLatestScanLookupUsesIndex(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
seedScanned(t, store, 0, 20)
|
||||
|
||||
var plan []string
|
||||
require.NoError(t, store.db.Connection(func(tx *gorm.DB) error {
|
||||
if err := tx.Exec("SET enable_seqscan = off").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Raw(`EXPLAIN SELECT id, package_id FROM scan_results
|
||||
WHERE package_id IN (1, 2, 3)
|
||||
AND scanned_at = (SELECT MAX(x.scanned_at) FROM scan_results x WHERE x.package_id = scan_results.package_id AND x.deleted_at IS NULL)
|
||||
AND deleted_at IS NULL`).Scan(&plan).Error
|
||||
}))
|
||||
require.Contains(t, strings.Join(plan, "\n"), scanPackageScannedAtIndex)
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var dashboardEpoch = time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
type seedRow struct {
|
||||
registry, name, version, release string
|
||||
size int64
|
||||
downloads int
|
||||
}
|
||||
|
||||
// seedDashboard stores rows with distinct, increasing cache times so orderings are unambiguous.
|
||||
func seedDashboard(t *testing.T, store *GORMStoreV2, rows []seedRow) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for i, r := range rows {
|
||||
at := dashboardEpoch.Add(time.Duration(i) * time.Minute)
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: r.registry, Name: r.name, Version: r.version, ReleaseVersion: r.release,
|
||||
StorageKey: fmt.Sprintf("%s/%s/%s", r.registry, r.name, r.version),
|
||||
Size: r.size, CachedAt: at, LastAccessed: at,
|
||||
}))
|
||||
for d := 0; d < r.downloads; d++ {
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, r.registry, r.name, r.version))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dashboardFixture() []seedRow {
|
||||
return []seedRow{
|
||||
{"npm", "left-pad", "1.0.0", "", 100, 3},
|
||||
{"npm", "left-pad", "1.1.0", "", 110, 1},
|
||||
{"npm", "left-pad", "list", "", 5, 0}, // metadata page, never a row
|
||||
{"npm", "@scope/pkg", "2.0.0", "", 300, 0},
|
||||
{"npm", "react", "18.0.0", "", 900, 7},
|
||||
{"npm", "a_b", "1.0.0", "", 10, 0},
|
||||
{"npm", "axb", "1.0.0", "", 20, 0},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.zip", "v1.0.0", "", 500, 2},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.mod", "v1.0.0", "", 10, 0},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.info", "v1.0.0", "", 5, 0},
|
||||
{"go", "github.com/a/b/@v/v1.1.0.zip", "v1.1.0", "", 520, 0},
|
||||
{"go", "github.com/c/d/@v/v0.1.0.zip", "v0.1.0", "", 40, 1},
|
||||
{"pypi", "six", "six-1.17.0.tar.gz", "1.17.0", 60, 4},
|
||||
{"pypi", "six", "six-1.17.0-py2.py3-none-any.whl", "1.17.0", 20, 0},
|
||||
}
|
||||
}
|
||||
|
||||
func rowKeys(pkgs []*metadata.Package) []string {
|
||||
out := make([]string, len(pkgs))
|
||||
for i, p := range pkgs {
|
||||
out[i] = p.Registry + "/" + p.Name + "@" + p.Version
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// checkListPackageGroupsMatchesReference compares the SQL paging with the in-memory reference for many option sets.
|
||||
func checkListPackageGroupsMatchesReference(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedDashboard(t, store, dashboardFixture())
|
||||
all, err := store.ListPackages(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var cases []metadata.GroupListOptions
|
||||
for _, sortBy := range []string{"", metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize} {
|
||||
for _, desc := range []bool{false, true} {
|
||||
for _, filter := range []struct{ registry, q string }{
|
||||
{"", ""}, {"go", ""}, {"npm", ""}, {"nowhere", ""}, {"", "LEFT"}, {"", "1.17"}, {"", "a_b"}, {"", "github.com/a"}, {"", "no-such"},
|
||||
} {
|
||||
for _, size := range []int{0, 2, 3} {
|
||||
for page := 1; page <= 3; page++ {
|
||||
cases = append(cases, metadata.GroupListOptions{
|
||||
Registry: filter.registry, Query: filter.q, SortBy: sortBy, SortDesc: desc, Page: page, PageSize: size,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, opts := range cases {
|
||||
got, err := store.ListPackageGroups(ctx, opts)
|
||||
require.NoError(t, err, "%+v", opts)
|
||||
want := metadata.PageGroups(all, opts)
|
||||
require.Equal(t, want.TotalGroups, got.TotalGroups, "total groups %+v", opts)
|
||||
require.Equal(t, rowKeys(want.Packages), rowKeys(got.Packages), "rows %+v", opts)
|
||||
}
|
||||
}
|
||||
|
||||
func checkListPackageGroupsBehaviour(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedDashboard(t, store, dashboardFixture())
|
||||
|
||||
t.Run("metadata pages are not rows and Go variants collapse to the largest", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: "go"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(2), page.TotalGroups)
|
||||
require.ElementsMatch(t, []string{
|
||||
"go/github.com/a/[email protected]", "go/github.com/a/[email protected]", "go/github.com/c/[email protected]",
|
||||
}, rowKeys(page.Packages))
|
||||
for _, p := range page.Packages {
|
||||
if p.Version == "v1.0.0" && p.Name == "github.com/a/b" {
|
||||
require.EqualValues(t, 500, p.Size, "the .zip outranks .mod and .info")
|
||||
}
|
||||
}
|
||||
npm, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: "npm", Query: "left"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"npm/[email protected]", "npm/[email protected]"}, rowKeys(npm.Packages), "newest first, no list page")
|
||||
})
|
||||
|
||||
t.Run("a page holds whole groups and total_groups counts all groups", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Page: 1, PageSize: 2})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 8, page.TotalGroups)
|
||||
groups := map[string]bool{}
|
||||
for _, p := range page.Packages {
|
||||
groups[p.Registry+"/"+p.Name] = true
|
||||
}
|
||||
require.Len(t, groups, 2)
|
||||
require.Equal(t, "@scope/pkg", page.Packages[0].Name)
|
||||
})
|
||||
|
||||
t.Run("search treats LIKE wildcards literally", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Query: "a_b"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"npm/[email protected]"}, rowKeys(page.Packages))
|
||||
})
|
||||
|
||||
t.Run("search finds a release version", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Query: "1.17.0"})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page.Packages, 2)
|
||||
})
|
||||
|
||||
t.Run("an unknown registry is an empty page, not an error", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: "nowhere", PageSize: 5})
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, page.TotalGroups)
|
||||
require.Empty(t, page.Packages)
|
||||
})
|
||||
|
||||
t.Run("recent groups come first by cached_at", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{SortBy: metadata.GroupSortCachedAt, SortDesc: true, Page: 1, PageSize: 1})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "six", page.Packages[0].Name)
|
||||
})
|
||||
}
|
||||
|
||||
// checkDashboardStatementsAreConstant proves the statement count does not follow the row count.
|
||||
func checkDashboardStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
var counter *dbcount.Counter
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
|
||||
measure := func() map[string]int {
|
||||
out := map[string]int{}
|
||||
counter.Reset()
|
||||
_, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Page: 1, PageSize: 25, Query: "pkg"})
|
||||
require.NoError(t, err)
|
||||
out["groups"] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.ListPackageGroups(ctx, metadata.GroupListOptions{})
|
||||
require.NoError(t, err)
|
||||
out["all"] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.GetScanSummaries(ctx, nil, false)
|
||||
require.NoError(t, err)
|
||||
out["summaries"] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.GetRegistryStats(ctx)
|
||||
require.NoError(t, err)
|
||||
out["registry stats"] = counter.Count()
|
||||
return out
|
||||
}
|
||||
|
||||
seedScanned(t, store, 0, 10)
|
||||
small := measure()
|
||||
seedScanned(t, store, 10, 90)
|
||||
large := measure()
|
||||
t.Logf("statements for 10 rows %v, for 100 rows %v", small, large)
|
||||
require.Equal(t, small, large)
|
||||
require.LessOrEqual(t, large["groups"], 3, "count, keys, rows")
|
||||
require.LessOrEqual(t, large["summaries"], 2)
|
||||
}
|
||||
|
||||
// seedScanned stores n scanned packages, each with two scans so the latest-scan pick is exercised.
|
||||
func seedScanned(t *testing.T, store *GORMStoreV2, from, n int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for i := from; i < from+n; i++ {
|
||||
name := fmt.Sprintf("pkg-%03d", i)
|
||||
at := dashboardEpoch.Add(time.Duration(i) * time.Minute)
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name,
|
||||
Size: 10, CachedAt: at, LastAccessed: at,
|
||||
}))
|
||||
for _, scanner := range []string{"old", "new"} {
|
||||
scan := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: scanner,
|
||||
Status: metadata.ScanStatusClean, ScannedAt: at,
|
||||
}
|
||||
if scanner == "new" {
|
||||
scan.ScannedAt = at.Add(time.Hour)
|
||||
}
|
||||
require.NoError(t, store.SaveScanResult(ctx, scan))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func checkScanSummaries(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedDashboard(t, store, []seedRow{
|
||||
{"npm", "clean", "1.0.0", "", 1, 0},
|
||||
{"npm", "bad", "1.0.0", "", 1, 0},
|
||||
{"npm", "broken", "1.0.0", "", 1, 0},
|
||||
{"npm", "lost", "1.0.0", "", 1, 0},
|
||||
{"npm", "unscanned", "1.0.0", "", 1, 0},
|
||||
})
|
||||
save := func(name string, res *metadata.ScanResult) {
|
||||
res.Registry, res.PackageName, res.PackageVersion = "npm", name, "1.0.0"
|
||||
require.NoError(t, store.SaveScanResult(ctx, res))
|
||||
}
|
||||
save("clean", &metadata.ScanResult{Scanner: "a", Status: metadata.ScanStatusVulnerable, ScannedAt: dashboardEpoch,
|
||||
VulnerabilityCount: 1, Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: "low"}}})
|
||||
save("clean", &metadata.ScanResult{Scanner: "b", Status: metadata.ScanStatusClean, ScannedAt: dashboardEpoch.Add(time.Hour)})
|
||||
save("bad", &metadata.ScanResult{Scanner: "a", Status: metadata.ScanStatusVulnerable, ScannedAt: dashboardEpoch, VulnerabilityCount: 3,
|
||||
Vulnerabilities: []metadata.Vulnerability{
|
||||
{ID: "CVE-2", Severity: "critical"}, {ID: "CVE-3", Severity: "HIGH"}, {ID: "CVE-4", Severity: "medium"},
|
||||
}})
|
||||
save("broken", &metadata.ScanResult{Scanner: "a", Status: metadata.ScanStatusError, ScannedAt: dashboardEpoch,
|
||||
Details: map[string]interface{}{"infrastructure_error": true}})
|
||||
require.NoError(t, store.db.Model(&PackageModel{}).Where("name = ?", "lost").Update("security_scanned", true).Error)
|
||||
|
||||
byName := func(sums []*metadata.ScanSummary) map[string]*metadata.ScanSummary {
|
||||
m := map[string]*metadata.ScanSummary{}
|
||||
for _, s := range sums {
|
||||
m[s.Name] = s
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
all, err := store.GetScanSummaries(ctx, nil, false)
|
||||
require.NoError(t, err)
|
||||
sums := byName(all)
|
||||
require.Len(t, sums, 4, "the unscanned package has no summary")
|
||||
|
||||
require.Equal(t, metadata.ScanStatusClean, sums["clean"].Status, "the later scan wins")
|
||||
require.Zero(t, sums["clean"].Total)
|
||||
require.Equal(t, "npm", sums["clean"].Registry)
|
||||
|
||||
bad := sums["bad"]
|
||||
require.Equal(t, 3, bad.Total)
|
||||
require.Equal(t, [4]int{1, 1, 1, 0}, [4]int{bad.Critical, bad.High, bad.Moderate, bad.Low})
|
||||
require.Nil(t, bad.Vulnerabilities, "the list is loaded only on request")
|
||||
|
||||
require.Equal(t, metadata.ScanStatusError, sums["broken"].Status)
|
||||
require.Equal(t, true, sums["broken"].Details["infrastructure_error"], "failed scans always carry their details")
|
||||
|
||||
require.False(t, sums["lost"].HasScan)
|
||||
|
||||
withList, err := store.GetScanSummaries(ctx, []string{sums["bad"].PackageID, sums["clean"].PackageID}, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, withList, 2)
|
||||
require.Len(t, byName(withList)["bad"].Vulnerabilities, 3)
|
||||
require.Equal(t, "CVE-2", byName(withList)["bad"].Vulnerabilities[0].ID)
|
||||
|
||||
none, err := store.GetScanSummaries(ctx, []string{}, false)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, none)
|
||||
}
|
||||
|
||||
func checkRegistryStats(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
seedDashboard(t, store, dashboardFixture())
|
||||
stats, err := store.GetRegistryStats(context.Background())
|
||||
require.NoError(t, err)
|
||||
got := map[string]metadata.RegistryStat{}
|
||||
for _, s := range stats {
|
||||
got[s.Registry] = s
|
||||
}
|
||||
require.Equal(t, metadata.RegistryStat{Registry: "npm", Count: 6, Size: 100 + 110 + 300 + 900 + 10 + 20, Downloads: 3 + 1 + 7}, got["npm"], "the list page is excluded")
|
||||
require.Equal(t, metadata.RegistryStat{Registry: "go", Count: 5, Size: 500 + 10 + 5 + 520 + 40, Downloads: 3}, got["go"])
|
||||
require.Equal(t, metadata.RegistryStat{Registry: "pypi", Count: 2, Size: 80, Downloads: 4}, got["pypi"])
|
||||
}
|
||||
|
||||
func TestListPackageGroupsMatchesReference(t *testing.T) {
|
||||
checkListPackageGroupsMatchesReference(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestListPackageGroupsBehaviour(t *testing.T) {
|
||||
checkListPackageGroupsBehaviour(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestDashboardStatementsAreConstant(t *testing.T) {
|
||||
checkDashboardStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestScanSummaries(t *testing.T) { checkScanSummaries(t, newTimeSeriesStore(t)) }
|
||||
func TestRegistryStats(t *testing.T) { checkRegistryStats(t, newTimeSeriesStore(t)) }
|
||||
|
||||
// checkScanIndexMigration drops the index and proves the migration restores it, twice over.
|
||||
func checkScanIndexMigration(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
m := store.db.Migrator()
|
||||
require.True(t, m.HasIndex(&ScanResultModel{}, scanPackageScannedAtIndex), "a fresh schema carries the index")
|
||||
require.NoError(t, m.DropIndex(&ScanResultModel{}, scanPackageScannedAtIndex))
|
||||
require.False(t, m.HasIndex(&ScanResultModel{}, scanPackageScannedAtIndex))
|
||||
|
||||
for _, migration := range GetMigrations() {
|
||||
if migration.ID != "202611240001" {
|
||||
continue
|
||||
}
|
||||
require.NoError(t, migration.Migrate(store.db))
|
||||
require.NoError(t, migration.Migrate(store.db), "rerun must be a no-op")
|
||||
require.True(t, m.HasIndex(&ScanResultModel{}, scanPackageScannedAtIndex))
|
||||
return
|
||||
}
|
||||
t.Fatal("migration 202611240001 is not registered")
|
||||
}
|
||||
|
||||
func TestScanIndexMigration(t *testing.T) { checkScanIndexMigration(t, newTimeSeriesStore(t)) }
|
||||
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListPackageGroupsMatchesReference() {
|
||||
checkListPackageGroupsMatchesReference(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListPackageGroupsBehaviour() {
|
||||
checkListPackageGroupsBehaviour(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_DashboardStatementsAreConstant() {
|
||||
checkDashboardStatementsAreConstant(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ScanSummaries() { checkScanSummaries(s.T(), s.store) }
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_RegistryStats() { checkRegistryStats(s.T(), s.store) }
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ScanIndexMigration() { checkScanIndexMigration(s.T(), s.store) }
|
||||
@@ -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
|
||||
@@ -102,6 +103,12 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Driver == "sqlite" {
|
||||
if err := ensureSQLiteStatsIndexes(db); err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to create stats indexes")
|
||||
}
|
||||
}
|
||||
|
||||
if err := dropEmptyTable(db, legacyDownloadEventsTable); err != nil {
|
||||
log.Warn().Err(err).Str("table", legacyDownloadEventsTable).Msg("Failed to drop empty legacy table")
|
||||
}
|
||||
@@ -118,10 +125,17 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// History must exist before the worker writes today's snapshot.
|
||||
if days, err := BackfillStatsSnapshots(context.Background(), db, time.Now()); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to backfill stats snapshots")
|
||||
} else if days > 0 {
|
||||
log.Info().Int("days", days).Msg("Backfilled stats snapshots")
|
||||
}
|
||||
|
||||
// Start aggregation worker (skip for in-memory databases used in tests)
|
||||
if !strings.Contains(cfg.DSN, ":memory:") {
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
go store.aggregationWorker.Start()
|
||||
store.aggregationWorker.StartAsync()
|
||||
} else {
|
||||
// For tests: create worker but don't start it
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
@@ -490,7 +504,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 +520,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
|
||||
@@ -623,6 +686,12 @@ func (s *GORMStoreV2) GetStats(ctx context.Context, registry string) (*metadata.
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// DB exposes the GORM handle for tests.
|
||||
func (s *GORMStoreV2) DB() *gorm.DB { return s.db }
|
||||
|
||||
// WrapDB replaces the handle with wrap(handle). Tests use it to count statements; call it before concurrent use.
|
||||
func (s *GORMStoreV2) WrapDB(wrap func(*gorm.DB) *gorm.DB) { s.db = wrap(s.db) }
|
||||
|
||||
// Health checks database connectivity
|
||||
func (s *GORMStoreV2) Health(ctx context.Context) error {
|
||||
sqlDB, err := s.db.DB()
|
||||
@@ -651,6 +720,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 +736,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 +788,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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,41 +988,7 @@ func (s *GORMStoreV2) GetScanResult(ctx context.Context, registry, name, version
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to retrieve scan result")
|
||||
}
|
||||
|
||||
// Extract vulnerabilities from Details
|
||||
var vulnerabilities []metadata.Vulnerability
|
||||
if vulnData, ok := scanModel.Details["vulnerabilities"]; ok {
|
||||
// The vulnerabilities are stored as []interface{} after JSON unmarshaling
|
||||
if vulnArray, ok := vulnData.([]interface{}); ok {
|
||||
for _, v := range vulnArray {
|
||||
if vulnMap, ok := v.(map[string]interface{}); ok {
|
||||
vuln := metadata.Vulnerability{
|
||||
ID: getStringFromMap(vulnMap, "id"),
|
||||
Severity: getStringFromMap(vulnMap, "severity"),
|
||||
Title: getStringFromMap(vulnMap, "title"),
|
||||
Description: getStringFromMap(vulnMap, "description"),
|
||||
FixedIn: getStringFromMap(vulnMap, "fixed_in"),
|
||||
}
|
||||
// Extract references array
|
||||
if refs, ok := vulnMap["references"].([]interface{}); ok {
|
||||
for _, ref := range refs {
|
||||
if refStr, ok := ref.(string); ok {
|
||||
vuln.References = append(vuln.References, refStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Extract detected_by array
|
||||
if detectedBy, ok := vulnMap["detected_by"].([]interface{}); ok {
|
||||
for _, db := range detectedBy {
|
||||
if dbStr, ok := db.(string); ok {
|
||||
vuln.DetectedBy = append(vuln.DetectedBy, dbStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
vulnerabilities = append(vulnerabilities, vuln)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
vulnerabilities := vulnerabilitiesFromDetails(scanModel.Details)
|
||||
|
||||
// Convert to metadata.ScanResult
|
||||
result := &metadata.ScanResult{
|
||||
@@ -977,11 +1024,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 +1040,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
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user